- Home /
C# cast object to gameobject not working
In script, I instantiate a NavMeshAgent. For some reason, it's impossible to cast the Object Instantiate creates to a GameObject, and therefore to do to get the NavMeshAgent properties. Here's my code:
public class RandomLocations : MonoBehaviour {
public int count = 10;
public float distX = 20.0f;
public float distY = 20.0f;
public Transform prefab;
// Use this for initialization
void Start () {
for (int i = 0; i < count; i++){
Vector3 position = new Vector3(Random.Range(-distX, distX), 0.0f, Random.Range(-distY, distY));
Object inst = Instantiate(prefab, position, Quaternion.identity); //results in (inst == something that seems right)
print("Created agent no. " + count);
GameObject instance = inst as GameObject; //After this, (instance == null).
}
}
Anyone have any idea what I'm doing wrong? :/ I'm completely new to Unity and C#, so feel free to state the obvious!
try GameObject instance = (GameObject) inst as GameObject or Instantiate(prefab, position , Quaternion.identity) as GameObject.
Answer by Tessa · May 18, 2012 at 11:40 AM
Nope, all your casting advises are not the solution:
GameObject instance = inst as GameObject;
does exactly the same. (As it should). However, I did find out what the problem was by now: the variable 'prefab' which was filled by dragging something there was declared as
public Transform prefab;
So it's not a GameObject but a Transform. Changing this declaration to
public GameObject prefab;
solved the problem!
for posting your own solution.
Now accept your answer (the round checkmark under the up/down vote icons on the left)
Answer by syclamoth · May 18, 2012 at 10:55 AM
Try this line instead:
GameObject inst = (GameObject)Instantiate(prefab, position, Quaternion.identity);
This or GameObject inst = Instantiate(prefab, position, Quaternion.identity) as GameObject;
are both viable options.