统一获取错误 GameObject.GetComponent()
Getting error GameObject.GetComponent() in unity
我正在使用这个 tutorial 为我的游戏统一开发观察者模式。这里是 Observer
class:
using UnityEngine;
using System.Collections;
namespace ObserverPattern
{
//Wants to know when another object does something interesting
public abstract class Observer
{
public abstract void OnNotify();
}
public class Box : Observer
{
//The box gameobject which will do something
GameObject boxObj;
//What will happen when this box gets an event
BoxEvents boxEvent;
public Box(GameObject boxObj, BoxEvents boxEvent)
{
this.boxObj = boxObj;
this.boxEvent = boxEvent;
}
//What the box will do if the event fits it (will always fit but you will probably change that on your own)
public override void OnNotify()
{
Jump(boxEvent.GetJumpForce());
}
//The box will always jump in this case
void Jump(float jumpForce)
{
//If the box is close to the ground
if (boxObj.transform.position.y < 0.55f)
{
boxObj.GetComponent().AddForce(Vector3.up * jumpForce);
}
}
}
}
但是,当我想要 运行 这个时,它给了我这个错误:
error CS0411: The type arguments for method 'GameObject.GetComponent()' cannot be inferred from the usage. Try specifying the type arguments explicitly.
错误在这一行:
boxObj.GetComponent().AddForce(Vector3.up * jumpForce);
有什么方法可以修复这个错误吗?
提前致谢
您需要在您的案例中添加模板参数
boxObj.GetComponent<Rigidbody>().AddForce(Vector3.up * jumpForce);
我正在使用这个 tutorial 为我的游戏统一开发观察者模式。这里是 Observer
class:
using UnityEngine;
using System.Collections;
namespace ObserverPattern
{
//Wants to know when another object does something interesting
public abstract class Observer
{
public abstract void OnNotify();
}
public class Box : Observer
{
//The box gameobject which will do something
GameObject boxObj;
//What will happen when this box gets an event
BoxEvents boxEvent;
public Box(GameObject boxObj, BoxEvents boxEvent)
{
this.boxObj = boxObj;
this.boxEvent = boxEvent;
}
//What the box will do if the event fits it (will always fit but you will probably change that on your own)
public override void OnNotify()
{
Jump(boxEvent.GetJumpForce());
}
//The box will always jump in this case
void Jump(float jumpForce)
{
//If the box is close to the ground
if (boxObj.transform.position.y < 0.55f)
{
boxObj.GetComponent().AddForce(Vector3.up * jumpForce);
}
}
}
}
但是,当我想要 运行 这个时,它给了我这个错误:
error CS0411: The type arguments for method 'GameObject.GetComponent()' cannot be inferred from the usage. Try specifying the type arguments explicitly.
错误在这一行:
boxObj.GetComponent().AddForce(Vector3.up * jumpForce);
有什么方法可以修复这个错误吗?
提前致谢
您需要在您的案例中添加模板参数
boxObj.GetComponent<Rigidbody>().AddForce(Vector3.up * jumpForce);