场景:
我在一个场景中有 10 个对象。每个对象都有一个唯一的附加类。单击一个对象时,需要调用两个方法。
- 附加到被点击游戏对象的脚本中的方法。 (启用新点击对象的用户界面)
- 来自先前点击的游戏对象的方法。 (禁用之前点击对象的用户界面)
我做了什么:
if (Physics.Raycast(ray, out hit)) {
hit.transform.GetComponent(hit.transform.name+"").Show_status (true);
current_transform.GetComponent(current_transform.name+"").Show_status(false);
current_transform = hit.transform;
}
在这里,我尝试使用字符串访问脚本,因为脚本是以游戏对象本身命名的。名为“Show_status()”的方法可用于所有类。上面的代码产生以下错误。
"UnityEngine.Component' does not contain a definition for `Show_status"
另外,如果我尝试的方式无法做到这一点,那么提及其他一些解决该场景的简单方法会很有帮助。
请您参考如下方法:
按名称访问游戏对象很慢。 hit.transform.name 很慢,每次调用时都会分配内存。通过字符串名称 (GetComponent(string)) 获取组件也很慢。
if this isn't possible the way I'm attempting it, it would be helpful to mention some other simple approaches to solving the scenario.
这可以通过 Interface 轻松完成。
创建一个名为 IClickable 的简单脚本 这不是一个类。它是一个接口(interface)。
public interface IClickable
{
void Show_status(bool value);
}
您的 10 脚本(在每个脚本中实现 IClickable):
脚本 1 调用了 ObjectToClick1。
public class ObjectToClick1 : MonoBehaviour, IClickable
{
//Implement your interface function
public void Show_status(bool value)
{
//Your implementation here
}
}
脚本 2 调用了 ObjectToClick2。
public class ObjectToClick2 : MonoBehaviour, IClickable
{
//Implement your interface function
public void Show_status(bool value)
{
//Your implementation here
}
}
Script3 调用了 ObjectToClick3。
public class ObjectToClick3 : MonoBehaviour, IClickable
{
//Implement your interface function
public void Show_status(bool value)
{
//Your implementation here
}
}
...
...
现在,对于点击部分并检测点击了哪个对象:
public class ObjectTest : MonoBehaviour
{
Transform current_transform;
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
//Raycast from mouse cursor pos
RaycastHit rayCastHit;
Ray rayCast = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(rayCast, out rayCastHit))
{
IClickable tempIClickable = rayCastHit.transform.GetComponent<IClickable>();
if (tempIClickable != null)
{
tempIClickable.Show_status(true);
current_transform.GetComponent<IClickable>().Show_status(false);
current_transform = rayCastHit.transform;
}
}
}
}
}
您可以添加尽可能多的接口(interface)。这非常灵活,可用于检测可用的敌人类型。
