[英]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.我正在尝试制作一个 Unity 游戏的一部分,其中气球将在盒子对撞机的范围内产生。 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
.这是第一种方法,这里我使用了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:这是第二种方法,我使用Vector2
和Quaternion
来尝试初始化 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'
.对于这两种方法,我都收到以下错误: 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.这让我难以置信,因为如果我将BalloonPrefab
设为 Vector2(这似乎不是解决方案但值得测试),它会要求 object,如果我将其设为 object,它似乎想要一个矢量2。 Does anyone know what the issue could be?有谁知道问题可能是什么?
I Think your For condition is also wrong and array think so我认为你的 For 条件也是错误的,数组也这么认为
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.