x


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!

more ▼

asked May 18 '12 at 10:36 AM

Tessa gravatar image

Tessa
37 3 3 5

try GameObject instance = (GameObject) inst as GameObject or Instantiate(prefab, position , Quaternion.identity) as GameObject.

May 18 '12 at 10:55 AM RoflHarris
(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

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!

more ▼

answered May 18 '12 at 11:40 AM

Tessa gravatar image

Tessa
37 3 3 5

+1 for posting your own solution.

Now accept your answer (the round checkmark under the up/down vote icons on the left)

May 18 '12 at 01:56 PM asafsitner
(comments are locked)
10|3000 characters needed characters left

Try this line instead:

GameObject inst = (GameObject)Instantiate(prefab, position, Quaternion.identity);
more ▼

answered May 18 '12 at 10:55 AM

syclamoth gravatar image

syclamoth
15k 7 15 80

This or GameObject inst = Instantiate(prefab, position, Quaternion.identity) as GameObject; are both viable options.

May 18 '12 at 11:06 AM asafsitner
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x4370
x2170
x1725
x1122
x31

asked: May 18 '12 at 10:36 AM

Seen: 2215 times

Last Updated: May 18 '12 at 01:56 PM