Хранить ссылки на объекты сцены в сборных? - PullRequest
0 голосов
/ 23 ноября 2018

Смотри, у меня есть игрок и враг на моей сцене.я использую vector2.movetowards, чтобы переместить моего врага в сторону моего игрока, но мой враг является префабом, поэтому я должен дать ему ссылку на моего игрока в инспекторе в качестве цели, но когда я удаляю врага со сцены, потому что это префаб, он удаляетссылка на плеер, что мне делать здесь, это мой код, спасибо, я просто хочу, чтобы как постоянно хранить ссылку на эту цель в префабе

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 Ответ

0 голосов
/ 23 ноября 2018

У вас есть несколько способов сделать это, но типичный - найти объект игрока, а затем сохранить целевую позицию, вы можете сделать это так:

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);
    }
}

Для Пути 3 вынеобходимо реализовать шаблон синглтона на вашем проигрывателе, он должен выглядеть следующим образом:

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
  }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...