Problem with instantiate ?!

Hello

I have a script like it :

	public GameObject [] obj;

void Spawn()
	{

		Object Masirobj = Instantiate (obj [Random.Range (0, obj.GetLength (0)) ], new Vector3 (transform.position.x, transform.position.y, transform.position.z - 10), Quaternion.identity);

	}

And I want to have a GameObject instead Object ( for instantiated object) but I have an error :
“Cannot implicitly convert type UnityEngine.Object' to UnityEngine.GameObject’. An explicit conversion exists (are you missing a cast?)”

Plz help me about that. Thanks

Well, the error message is trying to tell you exactly what’s wrong, and what to do about it:

  • You can’t implicitly convert a UnityEngine.Object (which is what Instantiate returns) to a UnityEngine.GameObject (which is what you want). An implicit conversion is what happens if you just try to assign directly, as you were doing, without any sort of cast.

  • But an explicit conversion exists. In other words, you can do this conversion with some sort of explicit cast.

  • C# is then so bold as to suggest that maybe you’re missing a cast. And it’s right. :slight_smile:

So, the solution is to use an explicit cast, e.g.:

         GameObject Masirobj = Instantiate (obj [Random.Range (0, obj.GetLength (0)) ], new Vector3 (transform.position.x, transform.position.y, transform.position.z - 10), Quaternion.identity) as GameObject

Cheers,

  • Joe

Thanks Joe, Solved.