'Cannot implicitly convert type 'UnityEngine.GameObject' to 'UnityEngine.Vector2'" While trying to Instantiate an object
I am trying to make a section of a Unity game where balloons will spawn within the bounds of a box collider. This is done randomly. However, I am having trouble Instantiating the prefab. I have tried two methods, with the same error being thrown for both.
This is the first method, here I used GameObject.transform.
for(int i = 0; i > numBalloons; i++){
float randomX = Random.Range(left, right);
float randomY = Random.Range(up, down);
balloons[i] = Instantiate(BalloonPrefab, BalloonPrefab.transform);
}
This was the second method, where I used a Vector2 and Quaternion to try and initialize the object:
for(int i = 0; i > numBalloons; i++){
float randomX = Random.Range(left, right);
float randomY = Random.Range(up, down);
Vector2 temp = new Vector2(randomX, randomY);
balloons[i] = Instantiate(BalloonPrefab, temp, Quaternion.identity);
}
}
For both methods, I get the following error:
Cannot implicitly convert type 'UnityEngine.GameObject' to 'UnityEngine.Vector2'. This is confusing me beyond belief, because if I make BalloonPrefab a Vector2 (which didn't seem to be a solution but was a worthy test), it asks for an object, and if I make it an object, it seems to want a Vector2. Does anyone know what the issue could be?
Solution 1:[1]
I Think your For condition is also wrong and array think so
public GameObject BalloonPrefab,ballon_parent;
public GameObject[] balloons;
void Start()
{
for (int i = 0; i < numBalloons; i++)
{
float randomX = Random.Range(left, right);
float randomY = Random.Range(up, down);
Instantiate(BalloonPrefab, new Vector2(randomX, randomY),Quaternion.identity, ballon_parent.transform);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | derHugo |
