GameObject.FindGameObjectWithTag 未检测到克隆的对象



我有一个脚本,可以根据它们的标签移动实例化的游戏对象。但是,已实例化的游戏对象不会移动。


实例化脚本:

void Update()
{
tillNextSpawn += Time.deltaTime;
Debug.Log(tillNextSpawn);
if (tillNextSpawn >= 2)
{
UnityEngine.Debug.Log("Instantiating circle");
screenPosition = Camera.main.ScreenToWorldPoint(new Vector3(Random.Range(0, Screen.width), Random.Range(0, Screen.height), Camera.main.farClipPlane / 2));
Instantiate(circle, screenPosition, Quaternion.identity);
tillNextSpawn = 0.0f;
}
}

敌人控制器脚本(移动敌人(

void FixedUpdate()
{
/*GameObject[]*/
var objects = GameObject.FindGameObjectsWithTag("Enemy");
var objectCount = objects.Length;
foreach (var obj in objects)
{
// Move the players accordingly
var rb = obj.GetComponent<Rigidbody2D>();
Debug.Log(rb);
Vector2 direction = (player.position - obj.transform.position).normalized;
rb.velocity = direction * moveSpeed;
}

}

你应该能够做到这一点,问题可能是你项目中的其他地方。 我创建了一个示例项目,该项目重新创建了您要执行的操作,并尝试与您发送的示例代码尽可能相似,您可以在此处找到它:

https://github.com/webocs/unity-so-sample-tags

据我所知,您的控制台正在发送异常

get_main is not allowed to be called...

我想到的是,该异常正在破坏整个执行,这就是为什么什么都没有发生的原因。

作为旁注,我不知道你的项目,所以我真的不知道你为什么要这样构建它。话虽如此,为什么不创建附加到敌方预制件的敌人脚本?如果你有很多敌人,你将在每次更新中发现并迭代所有这些敌人。如果创建敌人脚本并将其附加到预制件,您应该能够使用脚本附加到的游戏对象的变换来处理敌人的移动。这样,每个敌人都是一个独立的实体。

我希望所有这些都有所帮助!

编辑:我已经编辑了存储库并添加了一个名为"个人敌人"的场景,说明了我在评论中告诉您的内容

如果您希望敌人跟随玩家,请尝试执行以下操作:

//Attach this script to the enemy
Transform player;
private Rigidbody2D rb;
private Vector2 movement;
public float moveSpeed;
void Awake()
{
player = ScriptNameOnPlayer.instance.gameObject.transform;
}

// Start is called before the first frame update
void Start()
{
rb = this.GetComponent<Rigidbody2D>();
}
void Update()
{
Vector3 direction = player.position - transform.position;
direction.Normalize();
movement = direction;  
}
void FixedUpdate()
{
moveCharacter(movement);
}
void moveCharacter(Vector2 direction)
{
rb.MovePosition((Vector2)transform.position + (direction * moveSpeed * Time.deltaTime));
}

//But make sure your player script has this line of code:
public static ScriptNameOnPlayer instance;

希望这有帮助!

最新更新