Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
0
Question by gorevan · Dec 11, 2016 at 09:11 PM · transformspawnspawningpublicassign

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.

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
2
Best Answer

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.

Comment
Add comment · Show 7 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image gorevan · Dec 11, 2016 at 09:27 PM 0
Share

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

avatar image TBruce gorevan · Dec 11, 2016 at 09:38 PM 0
Share

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).

avatar image gorevan TBruce · Dec 11, 2016 at 09:41 PM 0
Share

Yes "public Transform playerTarget;" to be automatically assigned. Do you know a way around this then? ;/ @$$anonymous$$avina

Show more comments
Show more comments
avatar image TBruce · Dec 12, 2016 at 12:38 AM 0
Share

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

  1. messaboutEnemy-PauseController_NonStatic

  2. messaboutEnemy-PauseController_Static

Both packages include two script files.

  1. messaboutEnemy.cs (your file)

  2. 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.

avatar image gorevan TBruce · Dec 12, 2016 at 09:07 AM 0
Share

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!

avatar image
0

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!

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

87 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

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


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges