我如何确定在鼠标位置的对象类(Unity3d)
我在我的2D项目中有一个类(“foo”说),并且当我在鼠标位置获得对游戏对象的引用时,我想确定是否该对象属于foo类。我获得与我如何确定在鼠标位置的对象类(Unity3d)
GameObject objAtMouse = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(mousePos), Vector2.zero).transform.gameObject;
其中mousePos结构是我的鼠标的位置的对象,而且它似乎打算工作。为了测试I类曾尝试以下:
- 如果(objAtMouse是富){...}
- FOO fooAtMouse = objAtMouse为Foo; 如果(fooAtMouse){...}
- IF((objAtMouse.GetComponent( “富”)为富)!= NULL){...}
选项1.建议here是唯一的一个不产生错误,但产生了警告
给定表达式是从来没有提供的(“富”)型
选项2的,也是在上面的链接建议,产生错误
无法通过引用转换,装箱转换,解包转换,包装转换或null类型转换
选项3建议here并产生错误类型“UnityEngineGameObject”转换到“富”
的NullReferenceException:对象没有设置为一个对象的一个实例
这似乎是一个简单的任务,但我在这个问题上有点麻烦。那么,我怎样才能确定我鼠标结束的对象的类/类型?
任何帮助,非常感谢!
如果Foo
是一个组件,它可能是因为您将它附加到GameObject
,那么选项3非常接近。但你不需要投它as Foo
。
Foo fooComponent = objAtMouse.GetComponent<Foo>();
if (fooComponent == null) .. //no Foo component.
请注意,您应该检查是否objAtMouse
是null
第一..
场景中的所有对象是游戏物体本身并不会cild类。你想找到将组件
所以,你必须使用obj.GetComponents
把它弄出来游戏对象的其他类
你也可以为它分配一个标签,然后使用
objAtmouse.compareTag('your tag name');
首先,是第一线路不能正常工作:
GameObject objAtMouse = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(mousePos), Vector2.zero).transform.gameObject;
这假定你有一个不断的成功命中。
Raycast2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(mousePos), Vector2.zero);
if(hit.transform != null)
{
GameObject objAtMouse = hit.transform.gameObject;
if(objAtMouse.GetComponent<Foo>() != null){
// Object has component Foo on it
}
}
另一种解决办法是让富式讲述自己:
public class Foo:MonoBehaviour{
private static HashSet<Transform>fooCollection;
private void Awake()
{
if(fooCollection == null)
{
fooCollection = new HashSet<Transform>();
}
fooCollection.Add(this.transform);
}
private void OnDestroy()
{
fooCollection.Remove(this.transform);
}
public static bool CompareFooObject(Transform tr)
{
if(tr == null) return false;
return fooCollection.Contains(tr);
}
}
,那么你可以使用它作为:
Raycast2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(mousePos), Vector2.zero);
if(Foo.CompareFooObject(hit.transform))
{
// Is Foo type
}
的HashSet的优点是,它是相当快的找到物品。您还可以扩展该模式的用法,以便可以与任何类型的泛型一起使用,但我想现在就足够了。
Thank you for this answer,+1。我接受@林肯的答案作为检查无效性(你也提到)原来是这样的是关键,尽管还有其他的问题需要解决,他早点回答,干杯! – Rookatu
感谢您的回复:)我已经尝试了您的建议,但是我得到了上面列出的NullReferenceException。我错过了什么吗? – Rookatu
哪一行发生'NullReferenceException'?你有没有检查'objAtMouse'是否为'null'? – Lincoln
嗨。是的,我首先检查objAtMouse是否为null,并且只在所产生的if块中对fooComponent进行后续测试。错误发生在运行时;有没有办法获得有关哪条线导致错误的更多细节?谢谢! – Rookatu