当我尝试在manager类中实例化时,我遇到了错误。话
错误CS1061:键入UnityEngine.Object' does not contain a definition for
GetComponent',找不到扩展方法GetComponent' of type
UnityEngine.Object'。你错过了装配参考吗? (CS1061)(Assembly-CSharp)
答案 0 :(得分:1)
将此添加到您的Obstacle
课程:
void Start()
{
manager = GameObject.FindWithTag("ObstacleManager").GetComponent<ObstacleManager>();
}
标签显然必须是经理附加的游戏对象的标签。
另外:始终使用大写字母启动类名(我在代码段中做了这一点,记住这一点,你会得到一个错误的错误)。
也许你想要实际改变你的产卵。有两个列表,一个用于免费的spawnpoints,另一个用于被占用。当您摧毁障碍物时,将该位置传递给产卵功能以将位置移动到空闲列表。
修改强>:
创建引用的另一个选项是在产生ObstacleManager
时将其设置。您需要为此获取对实例化障碍的引用。我相信这应该可以在没有真正抓住障碍游戏对象的情况下工作,但你也可以这样做。
Obstacle obs = ((GameObject)Instantiate(TypeOfObstacles[j], pointsAvailiable[pointsIndex].position, Quaternion.identity)).GetComponent<Obstacle>();
obs.SetManagerReference(this);
在Obstacle
添加
public void SetManagerReference(ObstacleManager obsManager)
{
manager = obsManager;
}
对于自由职位,你可以这样做:
// in Obstacle.cs
public void OnMouseDown()
{
manager.SpawnNewObstacle(transform.position); // you might be able to actually pass the transform, but I'm not sure if it will get destroyed before used in the other function
Destroy(gameObject);
}
在经理中:
public int noOfObsacles;
public float[] xPercent;
public GameObject[] TypeOfObstacles;
float y;
// to keep track of which spawn points are free and which aren't use these lists
private List<Transform> freePositions;
private List<Transform> occupiedPositions;
private void Start()
{
freePositions = new List<Transform>(spawnPoints);
occupiedPositions = new List<Transform>();
SpawnObstacles();
}
private void SpawnObstacles()
{
// just use this for initial obstacles
// call Spawn as often as needed
for(int i = 0; i < noOfObstacles; i++)
{
Spawn();
}
}
// you call this function from the obstacle that gets destroyed
public void SpawnNewObstacle(Vector3 freePos)
{
// find the spawnpoint in the occupied points
// and move it to the free ones since the obstacle got destroyed
for(int i = 0; i < occupiedPositions.Count; i++)
{
if(occupiedPositions[i].position == freePos)
{
freePositions.Add(occupiedPositions[i]);
occupiedPositions.RemoveAt(i);
break;
}
}
// and call Spawn
Spawn();
}
private void Spawn()
{
y = Random.value;
int pointsIndex = Random.Range (0, freePositions.Count);
for (int j =0; j<xPercent.Length; j++)
{
if ( y < xPercent[j])
{
// these 4 lines are essential for the spawning
Obstacle obs = ((GameObject)Instantiate(TypeOfObstacles[j], freePositions[pointsIndex], Quaternion.identity).GetComponent<Obstacle>();
obs.SetManagerReference(this);
occupiedPositions.Add(freePositions[pointsIndex]);
freePositions.RemoveAt(pointsIndex);
break;
}
}
}
答案 1 :(得分:0)
有一个支架问题!我的不好
障碍物obs =((GameObject)Instantiate(TypeOfObstacles [j],freePositions [pointsIndex] .position,Quaternion.identity))。GetComponent();