Store References to Scene Objects in prefabs?

ⅰ亾dé卋堺 提交于 2021-02-04 20:59:19

问题


Look i have a player and enemy in my scene. i am using vector2.movetowards to move my enemy towards my player but my enemy is a prefab so i have to give it a reference of my player in the inspector as a target but when i delete enemy from scene because its a prefab it deletes the reference of the player what should i do here is my code thanks i just want that how to permanently store the reference of this target in prefab

using UnityEngine;
using System.Collections;

public class moveTowards : MonoBehaviour
{       
    public Transform target;
    public float speed;

    void Update()
    {
        float step = speed * Time.deltaTime;

        transform.position = Vector2.MoveTowards(transform.position, target.position, step);
    }
}

回答1:


You have several ways to do that, but the typical one is to find the player object, and then store the target position, you can do it like that:

using UnityEngine;
using System.Collections;

public class moveTowards : MonoBehaviour
{

    public Transform target; //now you can make this variable private!


    public float speed;

    //You can call this on Start, or Awake also, but remember to do the singleton player assignation before you call that function!   
    void OnEnable()
    {
      //Way 1 -> Less optimal
      target = GameObject.Find("PlayerObjectName").transform;

      //Way 2 -> Not the best, you need to add a Tag to your player, let's guess that the Tag is called "Player"
      target = GameObject.FindGameObjectWithTag("Player").transform;

      //Way 3 -> My favourite, you need to update your Player prefab (I attached the changes below)
      target = Player.s_Singleton.gameObject.transform;
    }

    void Update()
    {

        float step = speed * Time.deltaTime;


        transform.position = Vector2.MoveTowards(transform.position, target.position, step);
    }
}

For Way 3, you need to implement the singleton pattern on your Player, it should looks like that:

public class Player : MonoBehaviour
{

  static public Player s_Singleton;

  private void Awake(){
    s_Singleton = this; //There are better ways to implement the singleton pattern, but there is not the point of your question
  }

}


来源:https://stackoverflow.com/questions/53444030/store-references-to-scene-objects-in-prefabs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!