在预制件中存储对场景对象的引用? [英] Store References to Scene Objects in prefabs?

查看:64
本文介绍了在预制件中存储对场景对象的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看我的场景中有一个玩家和敌人.我正在使用vector2.movetowards将敌人移向我的玩家,但是我的敌人是预制的,所以我必须给它一个我在检查器中的玩家的参考作为目标,但是当我从场景中删除敌人时,因为它是预制的,所以它删除了播放器的引用我在这里应该做的是我的代码,谢谢,我只想知道如何将目标的引用永久存储在预制件中

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

推荐答案

您有几种方法可以做到这一点,但是典型的方法是找到玩家对象,然后存储目标位置,您可以像这样:

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

对于方法3,您需要在播放器上实施单人模式,看起来像这样:

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
  }

}

这篇关于在预制件中存储对场景对象的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆