Instantiate GameObject
Hello,
I am getting error in my script where I try to instantiate game object:
public int mapL, mapH;
public Transform[,] mapTransform;
void Start ()
{
mapL = 10;
mapH = 10;
mapTransform = new Transform[mapL,mapH];
Stuff();
}
void Stuff()
{
mapTransform[i,j]=Transform.Instantiate(grassButton, new Vector2(i,j), transform.rotation);
}
Cannot implicitly convert type UnityEngine.Object to UnityEngine.Transform. An explicit conversion exists (are you missing a cast?)
Same if I use public GameObject[,] mapTransform: Cannot implicitly convert type UnityEngine.Object to UnityEngine.GameObject. An explicit conversion exists (are you missing a cast?)
Can anyone tell me what I am doing wrong?
Answer by Suddoha · Sep 28, 2015 at 07:20 PM
You can fix that by using casts (boxing or the 'as' keyword).
someTransform = (Transform)Instantiate(....);
or
someTransform = Instantiate(...) as Transform;
The difference is, that 'as' might return null when the object cannot be casted, whereas the boxing approach would throw an InvalidCastException.
Answer by DCrosby · Sep 28, 2015 at 06:30 PM
Don't count this as "Expert" advice, since I'm struggling with similar issues, but on the instantiating materials on the instantiated geo. But I think you're better off doing the whole thing as a GameObject, as a transform has to have a "Parent" to live under, and GameObject is the lowest common denominator, and most likely what Unity is complaining about...
Your answer
![](https://koobas.hobune.stream/wayback/20220612035326im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Object to GameObject casting error c# (from object in scene not a prefab) 0 Answers
Parenting Instancing and Prefab issues 0 Answers
Using One Script for Two Separate Parent GameObjects Failing 0 Answers
Breaking Object by Destroying it and Instantiating Broken Parts problem, help! 2 Answers
LevelGenerator after Checkpoint Respawn Not Aligning Tiles Properly 1 Answer