Constructing an unbounded function really does seem to me to be the easiest approach. One very natural way to do this is to find a countably infinite, closed, discrete subset $D=\{x_n:n\in\Bbb N\}$ of $X$. If we can do this, we the function $f:D\to\Bbb R:x_n\mapsto n$ will be continuous (since $D$ is discrete), and by the Tietze extension theorem it will have a continuous extension $g$ to all of $X$ (since $D$ is closed in $X$). Clearly this $g$ is unbounded.
At this point you can use some general results:
- A metric space is compact if and only if it is countably compact.
- A $T_1$ space is countably compact if each infinite subset of $X$ has a limit point.
Thus, if $X$ is not compact, then it’s not countably compact, and therefore it has an infinite closed discrete subset $D_0$. We can then take $D$ to be any countably infinite subset of $D_0$.
Alternatively, you can get your hands dirty and directly construct the desired set $D$. If $X$ is not compact, then either $X$ is unbounded, or $X$ is not closed.
If $X$ is not bounded, we can assume without loss of generality that it contains arbitrarily large positive real numbers. Let $x_0$ be one of these. Given $x_n$, there is an $x_{n+1}\in X$ such that $x_{n+1}\ge x_n+1$. In this way we can recursively construct the set $D=\{x_n:n\in\Bbb N\}$, and it’s easy to check that $D$ is a closed, discrete subset of $X$ (and indeed of $\Bbb R$).
If $X$ is not closed, let $x\in(\operatorname{cl}X)\setminus X$. Pick $x_0\in X$ arbitrarily. Given $x_n\in X$, let $r_n=|x_n-x|$; $x$ is in the closure of $X$, so there is an $x_{n+1}\in B\left(x,\frac{r_n}2\right)\cap X$. Thus we can recursively construct a sequence $\sigma=\langle x_n:n\in\Bbb N\rangle$ of distinct points of $X$ such that $\sigma$ converges to $x$. Now let $D=\{x_n:n\in\Bbb N\}$; the only limit point of $D$ in $\Bbb R$ is $x$, which is not in $X$, so $D$ is a closed, discrete subset of $X$ (in the relative topology on $X$).