5. Given the function $y=-x^{2}+a x-\frac{a}{4}+\frac{1}{2}(0 \leqslant$ $x \leqslant 1$ ) has a maximum value of 2. Then the range of the real number $a$ is ( ).
(A) $0 \leqslant a \leqslant 2$
(B) $a2$
(C) $a=3$ or $a=-2$
(D) $a=-6$ or $a=\frac{10}{3}$
5.D.
$$
\begin{array}{l}
y=-x^{2}+a x-\frac{a}{4}+\frac{1}{2} \\
=-\left(x-\frac{a}{2}\right)^{2}+\frac{a^{2}-a+2}{4} .
\end{array}
$$
(1) If $x=\frac{a}{2}$ is to the left of $0 \leqslant x \leqslant 1$, then $\frac{a}{2}<0 \Rightarrow a<0$.
If $x=\frac{a}{2}$ is to the right of $0 \leqslant x \leqslant 1$, then $\frac{a}{2}>1 \Rightarrow a>2$.
Therefore, when $x=1$, $y_{\text {max }}=\frac{3}{4} a-\frac{1}{2}=2$.
Solving for $a$ gives $a=\frac{10}{3}>2$.
Hence, when $a=\frac{10}{3}$, $y_{\text {max }}=2$.
(3) If $x=\frac{a}{2}$ is within $0 \leqslant x \leqslant 1$, then $0 \leqslant \frac{a}{2} \leqslant 1 \Rightarrow 0 \leqslant a \leqslant 2$.
Therefore, when $x=\frac{a}{2}$, $y_{\max }=\frac{a^{2}-a+2}{4}=2$.
Solving for $a$ gives $a=3$ or $a=-2$.
But $a=3$ or $a=-2$ are not within $0 \leqslant a \leqslant 2$.
Thus, when $0 \leqslant a \leqslant 2$, the maximum value of the function cannot be 2.
In summary, when $y_{\max }=2$, $a=-6$ or $a=\frac{10}{3}$.