使用AddComponent访问自定义属性

时间:2014-03-06 12:35:17

标签: c# unity3d

在Unity3D中,我有一个脚本可以将变量'eaten'添加为组件。

using UnityEngine;
[AddComponentMenu("My game/IsEaten")] 
public class IsEaten : MonoBehaviour 
{ 
    public bool Eaten; 
}

耶!然后我可以添加另一个脚本来访问'Eaten'

using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour
{
    private Eaten someScript;

    // Use this for initialization
    void Start ()
    {
        someScript = GetComponent<IsEaten>();
        bool temp = someScript.Eaten;
        print(temp); // false
    }
}

哪个工作正常。如何从另一个脚本使用点表示法访问变量?即

if (myCube.eaten == true)
{
    // do something
}

2 个答案:

答案 0 :(得分:0)

你知道,在Unity中,很少创建整个脚本来向某个对象添加单个属性。常见的方法是将脚本视为“组件”(实际上它们是“组件”)。让我解释一下,组件是一段代码,可以为GameObject添加某些功能,比如制作动画或表现物理定律的能力。所以,也许,最好改进你的IsEaten类来形成一个真正的组件,比如Pickup(我假设你需要Eaten属性来获取某种类型的东西)这将具有玩家可以吃的功能,或者什么。

// You will actually need to attach a collider (and check the 'IsTrigger' checkbox on it) to your GameObject
// Then this method will be called whenewer some game object with a collider (e. g. player, npc's, monsters) will enter the trigger of this object
void OnTriggerEnter(Collider other)
{
    // Check whether this object was eaten before and if the actor entering our trigger is actually the player
    if (!Eaten && other.tag == "Player")
    {
        // Make shure that we will not get eaten twice
        Eaten = true;
        // Apply some effect to the player that has devoured us
        other.GetComponent<Player>().AddHp(25);
    }
}

除此之外,我个人在想,只是简单地启用一些更甜美的语法并不值得麻烦,但是,如果你提供一些有关你实际尝试实现的内容的见解,我可能会试着帮助你:)

答案 1 :(得分:0)

一种方法可能是使用Get / Set:

using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour
{


    private Eaten someScript;

    // start new!
    public bool eaten
    {

        get
        {
            return someScript.Eaten;
        }

        set
        {
            someScript.Eaten = value;
        }
    }
    // end new!

    // Use this for initialization
    void Start ()
    {
        someScript = GetComponent<IsEaten>();
        bool temp = someScript.Eaten;
        print(temp); // false
    }
}

然后您可以访问Test类属性:

Test t = GetComponent<Test>();
t.eaten = true;

ATH。