How to automatically assign a Transform?
Hi guys, thank you for your time.
I am creating an enemy spawning system. The enemy script I use requires me to assign a 'public Transform playerTarget;' so it can actually find the player and attack. However whenever I use my spawn system it spawns the enemies but they cannot move as they do not have the 'public Trasnform playerTarget;' assigned as I have to do it manually by dragging it into the inspector.
How would I automatically assign this Transform without having to drag it in each time? The game of course can't function if every time an enemy spawns I need to assign this in the inspector.
Thanks guys and I really do appreciate any help that people will give me.
Answer by TBruce · Dec 11, 2016 at 09:22 PM
Are you looking for something like this
public Transform playerTarget;
public float moveSpeed = 3.0f;
void Start ()
{
if (GameObject.FindWithTag("Player") != null)
{
playerTarget = GameObject.FindWithTag("Player").transform;
}
}
// Update is called once per frame
void Update ()
{
if (playerTarget != null)
{
transform.position = Vector3.MoveTowards (transform.position, playerTarget.position, moveSpeed * Time.deltaTime);
}
}
where the script attached to the enemy seeks the player.
No, I am looking for a way to automatically assign the transform. Sorry if I haven't explained properly.
The "public Transform playerTarget" needs to be assigned via inspector and I need to drag the gameObject into the slot for the transform. I don't want to do that though. I want my script to automatically assign this gameobject to the transform slot in the inspector.
using "playerTarget = GameObject.FindWithTag("Player").transform; " you would think would work however it doesn't assign it. I've already tried that!
I really do appreciate you trying to help me:) @$$anonymous$$avina
You say you want to automatically assign the transform
. Are you referring to the
public Transform playerTarget;
It can only be automatically assigned at runtime. You can not assign it in the constructor (when the script is added to a game object).
Yes "public Transform playerTarget;" to be automatically assigned. Do you know a way around this then? ;/ @$$anonymous$$avina
Is PauseController static? If not you need to change all references of PauseController.XP$$anonymous$$oney
to pc.XP$$anonymous$$oney
. Nevertheless here is a link to a zip file with two unity packages. The packages are as follows
messaboutEnemy-PauseController_NonStatic
messaboutEnemy-PauseController_Static
Both packages include two script files.
messaboutEnemy.cs (your file)
messaboutEnemyEditor.cs (the custom editor)
The custom editor is the same in both packages so all you need to do is import the custom editor. It will automatically be placed in the folder Assets\Editor
.
I have done a basic test using a simple terrain, a cube (as the enemy) and a capsule as the player. On game start the enemy searches and finds the player. If I move the player back and fort around the screen the enemy cube changes direction towards the player capsule.
BTW, people offer there time free on this site so donations are not required but thank you for the thought. All that is ever asked is that if you find an answer helpful that you click the Accept button to accept the answer. And if you really like it you can Upvote the answer as well.
Hi this work perfectly. Thank you very very much for your time and I really do appreciate it. I have one more problem tho however I know need a wait to automatically assign "public Slider healthbar;" or to create a slider each time an enemy is created. I only use the healthbar however for it's values. Would there be a better way to use this?
Thank you again and you deserve a donation my friend for your generosity!
Answer by gorevan · Dec 11, 2016 at 10:40 PM
using UnityEngine; using System.Collections; using UnityEngine.UI;
public class messaboutEnemy : MonoBehaviour { public float sinkSpeed = 0.2f; //The speed at which the enemy sinks through the floor when dead public int damageAmount = 10;
public Transform playerTarget; //Getting players position for enemy to follow
public Slider healthbar; //Reference for enemy health (visuals of bar isn't actually used. Is actually just for the values)
public Toggle fullscreenToggle;
[SerializeField]
private int upgradeCost = 100;
NavMeshAgent pathfinder; //Reference to Nav Mesh Agent for enemy movement
Animator anim; //Reference to animator (for calling animations of enemy)
AudioSource audioPlay; //Reference to AudioSource
SphereCollider enemyCollider; //Reference to SphereCollider
CapsuleCollider enemyCapsule; //Reference to CapsuleCollider
PauseController pc; //Reference to PauseController
bool isSinking; //Whether the enemy has started sinking through the floor.
void Start()
{
//Setting up references
pathfinder = GetComponent<NavMeshAgent>();
anim = GetComponent<Animator>();
audioPlay = GetComponent<AudioSource>();
enemyCollider = GetComponent<SphereCollider>();
enemyCapsule = GetComponent<CapsuleCollider>();
pc = GetComponent<PauseController>();
damageAmount = 10;
}
void Update()
{
if (healthbar.value <= 0) return; //If the enemies health is less than or equal to 0 then it will not return the function below
if (Vector3.Distance(playerTarget.position, this.transform.position) < 50) //If the distance between player and enemy is less than 50 then...
{
pathfinder.enabled = true; //Pathfinding will be enabled
pathfinder.SetDestination(playerTarget.position); //Set enemies location to the location of the player
anim.SetBool("isWalking", true); //Walking animation enabled
anim.SetBool("isAttacking", false); //Attacking animation disabled
anim.SetBool("isIdle", false); //Idle animation disabled
if (isSinking) //If the enemy is sinking...
{
transform.Translate(-Vector3.up * sinkSpeed * Time.deltaTime); //move the enemy down under the terrain by the sinkSpeed per second.
}
}
Vector3 direction = playerTarget.position - this.transform.position; //Defining direction (subtracting the players position from that of the enemies position)
if (direction.magnitude > 50) //If distance between player and enemy is greater than 50 then...
{
pathfinder.SetDestination(this.transform.position); //Enemy stops walking towards player
anim.SetBool("isIdle", true); //Idle animation enabled
anim.SetBool("isWalking", false); //Walking animation disabled
anim.SetBool("isAttacking", false); //Attacking animation disabled
anim.SetBool("isGettingHit", false); //Getting hit animation deactivated
}
if (Vector3.Distance(playerTarget.position, this.transform.position) < 3) //If distance between player and enemy is greater than 3 then...
{
pathfinder.SetDestination(this.transform.position); //Enemy stops walking towards player
anim.SetBool("isAttacking", true); //Attacking animation enabled
anim.SetBool("isWalking", false); //Walking animation disabled
anim.SetBool("isIdle", false); //Idle animation disabled
}
}
void OnTriggerEnter(Collider collider)
{
if (collider.tag == "Enemy Hit Collider")
return;
if (collider.tag == "Player Attack Collider") //If players collider enters that of the enemies then...
{
anim.SetBool("isGettingHit", true); //Getting hit animation activated
anim.SetBool("isWalking", false); //Walking animation will not play
anim.SetBool("isAttacking", false); //Attacking animation will not play
anim.SetBool("isIdle", false); //Idle animation will not play
healthbar.value -= damageAmount; //Take damageAmount off of enemy when collider hits enemy
if (healthbar.value <= 0) //If enemies health is less than or equal to 0 then...
{
enemyCollider.enabled = false; //Disable SphereCollider to stop glitch where death sound would play several times
enemyCapsule.enabled = false; //Disable CapsuleCollider to stop glitch where death sound would play several times
Object.Destroy(gameObject, 6); //Enemys body will be destroyed after 5 seconds, for efficency.
pathfinder.SetDestination(this.transform.position); //Enemy stops walking towards player
anim.SetBool("isDead", true); //Play death animation
anim.SetBool("isWalking", false); //Walking animation will not play
anim.SetBool("isAttacking", false); //Attacking animation will not play
anim.SetBool("isIdle", false); //Idle animation will not play
anim.SetBool("isGettingHit", false); //Getting hit animation deactivated
audioPlay.volume = Random.Range(0.5f, 0.7f); //Random volume between values
audioPlay.pitch = Random.Range(0.8f, 1.2f); //Random pitch between values
audioPlay.Play(); //Play death sound
PauseController.XPMoney += Random.Range(7, 15); //Add 10XP to XPMoney
}
}
else
{
anim.SetBool("isGettingHit", false); //If the enemy isn't getting hit, getting hit animation will be disabled
}
}
public void StartSinking()
{
pathfinder.enabled = false; //Enemy will stop moving
GetComponent<Rigidbody>().isKinematic = true; //Find rigidbody of enemy and make it kinematic (use Translate to sink enemy)
isSinking = true; //The enemy will sink
}
public void UpgradeMeleeAttack()
{
if (PauseController.XPMoney < upgradeCost)
{
return;
}
damageAmount += 10;
PauseController.XPMoney -= upgradeCost;
}
}
This is the entire script. That would be perfect! I am a student so I don't have much money but could I donate 10$ for the help you are giving. I really do appreciate this help my friend!
Your answer
Follow this Question
Related Questions
NetworkTransform did not working with RegisterSpawnHandlers 2 Answers
[C#] Only one instantiate object is working, the rest is not.. Help meee 0 Answers
How can i assign a GameObject to another but only have some of its components? 1 Answer
Networking concept and spawning questions 1 Answer
Lerp Confusion 1 Answer