- Home /
Why can't I get the transform from an instantiated object?
I'm instantiating an object (a signpost) and then trying to use its transform position as a base for defining where a textmesh is spawned. Thusly:
using UnityEngine;
using System.Collections;
public class spawntestscript : MonoBehaviour {
public Transform objectToSpawn ; //the prefab we're spawning
//public GameObject spawnedSign ; //just so we can see it in the inspector
public Transform newTextMesh ; //To define the text mesh for the 3D sign
// Use this for initialization
void Start () {
GameObject spawnedSign = Instantiate (objectToSpawn, transform.position, transform.rotation) as GameObject; //spawn the sign
Vector3 startPosition = spawnedSign.transform.position; //get the sign's position and set it as a variable
//Vector3 startPosition = spawnedSign.GetComponent<Transform>().position; //alternate method, same result
startPosition.x += 38; //move the start position
startPosition.y -=30;
//via the instantiate method
//We need to establish a start point and then += it after each block
GameObject text3d = Instantiate (newTextMesh, startPosition, Quaternion.Euler(0,0,0)) as GameObject; //create a text mesh at the adjusted start position
}
// Update is called once per frame
void Update () {
}
}
Yet what I'm getting is "NullReferenceException: Object reference not set to an instance of an object spawntestscript.Start () (at Assets/Scripts/spawntestscript.cs:18)"
I'm convinced it's something simple and fundamental, but I've been searching for solutions for hours now and I'm coming up blank. Help?
Answer by alexzzzz · Jun 22, 2013 at 05:59 PM
The object you try to instantiate is not a GameOject (objectToSpawn is declared as Transform), and since that the as operator returns null. So, spawnedSign is also null. I usually prefer to use direct cast over the as, because when something goes wrong it doesn't silently return null but immediately throws InvalidCastException.
Solution:
Transform spawnedSign = (Transform)Instantiate(objectToSpawn, transform.position, transform.rotation);
That did the trick, thank you. You're a gentleman and a scholar.