c# - 在预制件中存储对场景对象的引用?
问题描述
看我的场景中有一个玩家和一个敌人。我正在使用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);
}
}
解决方案
你有几种方法可以做到这一点,但典型的一种是找到玩家对象,然后存储目标位置,你可以这样做:
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,您需要在 Player 上实现单例模式,它应该如下所示:
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
}
}
推荐阅读
- c# - chromedriver 中的视频缓冲
- api - 将基于角色的访问控制 (RBAC) 方法置于 API 网关层之外
- ios - AVAssetWriter 编解码器类型 hevc
- python - 如何使用返回列表作为另一个函数的输入的函数?
- javascript - 如何使用 i18nextBrowserLanguageDetector 的结果
- scala - Scala中的矩阵乘法
- jenkins - 自动部署 Jenkins,Payara
- javascript - 调用服务将未翻译的文本保存在 ngx-translate 库中时,但我错了
- android - 如何使用 bigquery 选择列拆分的最后一个索引
- html - 闪亮应用的导航栏干扰 rmarkdown 网页的导航栏