1
\$\begingroup\$

Below is my code for a text I want to spawn under a canvas. Both spawn and I no longer get errors, but the text isn't spawning under the canvas.

        Instantiate(canvasparent);
        Text savescore = Instantiate(score) as Text;
        savescore.transform.SetParent(canvasparent.transform, false);
\$\endgroup\$
1
\$\begingroup\$

Remember to capture a reference to the instance of the object when you instantiate it, something like this:

Canvas canvasInstance = Instantiate<Canvas>(canvasPrefab);

Text scoreTextInstance = Instantiate<Text>(scoreTextPrefab);

scoreTextInstance.transform.SetParent(canvasInstance.transform, false);

The code you showed is trying to parent the newly-spawned text to the prefab of the canvas, not the instance of the canvas you've spawned into your scene.

This is probably the most common error I see in Unity code, so be very careful to keep track of which variables refer to spawned instances and which to prefabs.

\$\endgroup\$
  • \$\begingroup\$ Right, so i had to just do what i did in the second line in the first, thanks \$\endgroup\$ – wfa Sep 4 '16 at 6:30
  • \$\begingroup\$ but then i get these errors \$\endgroup\$ – wfa Sep 4 '16 at 6:33
  • \$\begingroup\$ Argument #1' cannot convert UnityEngine.GameObject' expression to type `UnityEngine.Canvas' \$\endgroup\$ – wfa Sep 4 '16 at 6:33
  • \$\begingroup\$ The best overloaded method match for `UnityEngine.Object.Instantiate<UnityEngine.Canvas>(UnityEngine.Canvas)' has some invalid arguments \$\endgroup\$ – wfa Sep 4 '16 at 6:33
  • \$\begingroup\$ Declare canvasPrefab as type Canvas instead of GameObject AlsoscoreTextPrefab as type Text instead of GameObject. Then assign them again in inspector. \$\endgroup\$ – Sourav Paul Sep 4 '16 at 9:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.