using UnityEngine;
public class PopulateAsteroids : MonoBehaviour {
public int NumAsteroids;
public GameObject gAsteroids;
// Use this for initialization
void Start ()
{
var Asteroid = Instantiate(gAsteroids);
Asteroid.transform.position = Vector3(1,1,1);
}
}
Why is this not working? It keeps telling me:
“Assets/Scripts/PopulateAsteroids.cs(11,26): error CS1061: Type UnityEngine.Object' does not contain a definition for transform’ and no extension method transform' of type UnityEngine.Object’ could be found (are you missing a using directive or an assembly reference?)”
Why is it not instantiating to a GameObject even though I explicitly tell it to?
New to unity, sorry.
I am aware that I can specify the position in the instantiate but that is not the point. I want to do so much more within the code.
Edit:
How the HELL do you use the code snippets? they are not working for me.
I fixed your code snipped, next time select all of it and hit the [1010101] button or put four spaces in front of every line.
You seem to be using C#'s var keyword but not understanding what it does. It’ll cast a variable to what is being written to it, in this case you use Instantiate() which returns an Object. You then try to access this objects .transform, which doesn’t exist. What you want to do is tell the variable you’re writing Insantiate to that it’s a GameObject.
var Asteroid = Instantiate(gAsteroids) as GameObject;
or
var Asteroid = (GameObject)Instantiate(gAsteroids);
it’s usually best do use the as keyword to downcast as it will return null if it can’t preform the cast. Do note that using the var keyword is considered by many as bad style in C#, since you can’t obviously see what type the variable is. So I would personally advice to do it without it:
GameObject Asteroid = Instantiate(gAsteroids) as GameObject;