在开发统一过程中,我们遇到了updata函数的一个问题:
!
发布于 2021-09-08 09:24:16
正如您已经提到的对象在播放器附近,而不是使用Update
,我会查看OnEnterTrigger
或OnEnterTrigger2D
,如果您的游戏是2D的。我不确定如何区分不同的动物--无论是标记、基类派生类、名称等等--但是在linq
上使用HashSet
应该可以很容易地在容器中找到特定的条目。如果你在你的问题上加上更多的信息,我可以缩小如何帮助的范围。我假设您有一个名为Animal
的基类,并将每个动物派生到自己的类,即Animal->Dog
或Animal->Cat
。这是一个相当通用的解决方案,如果您有问题,请告诉我。
对于这个片段,我假设这个脚本位于一个作为检测半径的球体或圆圈上。所有属于Animal
的对象都将tagged
作为Animal
,以便在动物进入玩家半径时更容易被检测。
Nearby.cs
using UnityEngine;
using System.Collections.Generic;
using System.Linq;
public class TestScript : MonoBehaviour
{
private HashSet<Animal> nearbyAnimals = new HashSet<Animal>();
private void OnTriggerEnter(Collider other)
{
if(other.tag == "Animal")
{
nearbyAnimals.Add(other.GetComponent<Animal>());
Debug.Log("Adding Animal!");
}
}
private void OnTriggerExit(Collider other)
{
if (other.tag == "Animal")
{
nearbyAnimals.Remove(other.GetComponent<Animal>());
Debug.Log("Removing Animal!");
}
}
private void Update()
{
// test - can be removed
if(Input.GetKeyDown(KeyCode.C))
{
FindNumberOfCatsNearby();
}
if(Input.GetKeyDown(KeyCode.Space))
{
FindNumberOfDogsNearby();
}
}
/// <summary>
/// Find the number of cats near the player
/// </summary>
private void FindNumberOfCatsNearby()
{
// simplified thanks for derHugo's comment
Debug.Log($"There are {nearbyAnimals.Count(animal => animal is Cat)} cats nearby", this);
}
/// <summary>
/// Find the number of dogs near the player
/// </summary>
private void FindNumberOfDogsNearby()
{
Debug.Log($"There are {nearbyAnimals.Count(animal => animal is Dog)} dogs nearby", this);
}
}
Animal.cs
using UnityEngine;
/// <summary>
/// Base class of all Animals
/// </summary>
public abstract class Animal : MonoBehaviour
{
protected abstract void AnimalMovement();
protected virtual void MakeAnimalSound() { }
}
您可以忽略我添加到类中的各种函数。他们在那里只是为了说明哪些东西可以用来区分每种动物的类型。
Cat.cs
using UnityEngine;
public class Cat : Animal
{
protected override void AnimalMovement()
{
// do unique cat movement
}
protected override void MakeAnimalSound()
{
Debug.Log("Meow");
}
}
Dog.cs
using UnityEngine;
public class Dog : Animal
{
protected override void AnimalMovement()
{
// do unique dog movement
}
protected override void MakeAnimalSound()
{
Debug.Log("Bark");
}
}
一旦进入,它就被添加到HashSet
中,一旦它离开,它就被移除。要找到一种类型Animal
的特定条目,可以使用我使用linq
作为示例的函数之一遍历它。您还可以使用HashSet
循环迭代遍历foreach
。
下面是脚本的一部分工作。在这个例子中,狗是立方体,猫是球体。
下面是我用来检测玩家进入动物半径时所用的部件。
这是其中一只动物的部件。除了它们上的派生类之外,它们都是相同的。
https://stackoverflow.com/questions/69106466
复制相似问题