首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在预制板中存储对场景对象的引用?

在预制板中存储对场景对象的引用?
EN

Stack Overflow用户
提问于 2018-11-23 09:37:42
回答 1查看 328关注 0票数 1

听着,我的场景里有一个玩家和一个敌人。我使用vtor2移动工具将我的敌人移向我的玩家,但我的敌人是预制板,所以我必须将我的玩家作为目标,但是当我从场景中删除敌人,因为它是预制件,它删除了玩家的引用,我应该做的是我的代码,谢谢,我只想永久地将这个目标的引用存储在预制件中。

代码语言:javascript
运行
复制
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);
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-23 09:50:16

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

代码语言:javascript
运行
复制
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,您需要在您的播放器上实现单例模式,它应该如下所示:

代码语言:javascript
运行
复制
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
  }

}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53444030

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档