我正在使用此tutorial为我的游戏开发统一的观察者模式。这是Observer
类:
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);
}
}
}
}
但是,当我要运行它时,出现此错误:
错误CS0411:无法从用法中推断出方法'GameObject.GetComponent()'的类型参数。尝试显式指定类型参数。
错误在此行上:
boxObj.GetComponent().AddForce(Vector3.up * jumpForce);
有什么办法可以纠正此错误?
提前感谢
您需要在这种情况下添加模板化参数
boxObj.GetComponent<Rigidbody>().AddForce(Vector3.up * jumpForce);