大家好,我正在尝试制作一个简单的2D游戏,这就是它的工作方式。假设有一个精灵“帐篷”,每当我单击帐篷时,控制台都会打印出一条消息。听起来很简单吗?但是我就像被困在其中一样,而且我知道在此之后我会如此努力地面对自己。我在脚本中所做的是:
public abstract class Player : MonoBehaviour {
protected string _name;
// Use this for initialization
public Player(string name)
{
_name = name;
}
public string Name
{
get { return _name; }
set { _name = value; }
}
void Start () {
}
// Update is called once per frame
void Update () {
}}
接下来,我有一个名为“平民”的子班
public class Civilian : Player {
// Use this for initialization
public Civilian(string name):base(name)
{
}
void Start () {
}
// Update is called once per frame
void Update () {
}
} 然后在我的脚本“ Tentclicked”中,我想在单击精灵时调用睡眠功能。
public class tentclicked : MonoBehaviour {
void OnMouseDown()
{
// c.Sleep();
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
您想知道c是什么,它指向什么?我在另一个名为testing1的脚本中实例化了一个新类。
public class testing1 : MonoBehaviour
{
public Text p1name;
public void Awake()
{
//p1name.text = "Hello";
//Civilian C = Scriptss.AddComponent<Civilian>();
//GameObject theCivilian = GameObject.Find("Scriptss");
// Civilian c = theCivilian.GetComponent<Civilian>();
//c.Name = Testingsavename.playernames.username;
//c.Name = "Hello";
}
// Use this for initialization
void Start()
{
if (Choosechar.choice.choicecount == 1)
{
Civilian c = new Civilian(Testingsavename.playernames.username);
p1name = GetComponent<Text>();
p1name.text = c.Name;
}
我已经在我的精灵上添加了一个对撞机。错误是在tentclicked中,c在上下文中不存在。所以我怀疑可能是团结不知道c是什么。我正在考虑将民用类设为静态类,并在tentclicked脚本中将其命名为Civilian.civilian.Sleep()。
答案 0 :(得分:1)
“ c”在此上下文中不存在,因为您的tentclicked
类没有对其的引用。用GameObject.Find(string name)
查找“ c”,并将游戏对象值分配给tentclicked
答案 1 :(得分:0)
您可以从当前鼠标位置向对象发出光线(只需确保该对象具有对撞机即可。
void OnMouseDown()
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if ( Physics.Raycast (ray,out hit,100.0f))
{
Civilian c = hit.collider.gameObject.GetComponent<Civilian>();
c.Sleep();
}
}