Prefab clone to target
How would i go about this you can do it on play game but then it reverts of course im just wondering how would you go about doing this as i need to have it done for my character.
The PlayerHealth is expose to use a clone prefab.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class UIManager : MonoBehaviour
{
public PlayerHealth playerHealth;
public Text HealthText;
private static bool UIExists;
// Use this for initialization
void Start()
{
if (!UIExists)
{
UIExists = true;
DontDestroyOnLoad(transform.gameObject);
}
else
{
Destroy(gameObject);
}
}
// Update is called once per frame
void Update()
{
HealthText.text = "" + playerHealth.currentHealth;
}
}
You'll need to change + playerHealth.currentHealth to
HealthText.text = "" + playerHealth.currentHealth.ToString();
And telling us what's actually not working would get a better response as well. Short, concise description of what the issue is will get a much better response. As well as posting any error messages.
Alright basically i have a prefab that isn't in scene until spawned (player) and i need him to be linked as a target for enemy AI to become aggressive towards but i cannot link it as target as it isn't in scene. Hope that explains more.
Answer by Mmmpies · Jun 11, 2016 at 02:24 PM
Typically you'd spawn the player first but I suppose it's up to you how you go about creating your game. There are a couple of ways of doing this.
In Update on the enemy scripts you can check if the the Player == null and if so look for it. It works but if you have a lot of enemies all looking for your player every single frame its an overhead.
You might be better having a script on the player prefab that in Start() searches for each enemy tagged object and calls a function FindPlayer to grab the newly instantiated prefab.
You need to tag each enemy and use FindGameObjectsWithTag and use a for each loop to go through each enemy and call the function to tell it to search for the player object.
This only happens once the player instantiates and is far lower as an overhead, all you need to do with the enemy script Update is
if(Player != null)
So it only tries to find/attack the player once it's instantiated.
Your answer
![](https://koobas.hobune.stream/wayback/20220612082644im_/https://answers.unity.com/themes/thub/images/avi.jpg)