fixelのブログ

Unity&C#初心者がイチからRTSを作るまでを書き記す日記

4回目・プレイヤーの変数を別のオブジェクトが参照する

C#のプレイヤー側のスクリプト名を「Player」、

別のオブジェクト側のスクリプト名を「Cursor」とし、

「Player」側で下記のプログラムを書いて、

direction = (GameObject)Resources.Load ("Prefabs/Cursor");
GameObject cursor = (GameObject)Instantiate (direction);
cursor.transform.parent = transform;

「Cursor」をプレハブから生成した後、

「Cursor」のparentを「Player」にすることで、

「Player」の取得をGetComponentではなく、GetComponentInParentで取得できるようにしてます。

 

「Player」側のスクリプトの変数

    public NavMeshAgent agent;
    public RaycastHit hit;
    public bool once = false;
    public bool targetF = false;

 

「Cursor」側のスクリプトの一部

    private Player _parent;

    void Start() {
        _parent = GetComponentInParent<Player>();
        transform.parent = null;
    }

    void Update() {
        if (_parent.once) {
            Object.Destroy (gameObject);

    } else {
            NavMeshPath path = _parent.agent.path;
            Vector3 _parentPO = _parent.transform.position;

 こうすることで「Cursor」が「Player」の値を参照できるようになりました。

「transform.position」は元々PublicでUnity側が作ってくれているので書かなくても参照できる。