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 /
avatar image
0
Question by DoWeLikeTurtles · Dec 27, 2018 at 06:32 PM · 2d gameontriggerenterontriggerexittargetingradius

Finding and assigning Target in radius (with colliders)

Hello! There's probably already many questions regarding this but I can't seem to find an answer that works for my problem! The problem I'm having is that I want my circle collider to not only tell my enemy if a gameobject with the tag "Player" enters the circle collider, but I also want the target to be equal to the gameobject with the "player" tag! As in, I want it to automatically find the tagged gameobject and make that the "target" rather than how it is set up currently where I assign a gameobject to the "public transform target"! Heres my code and if I can figure it out before anyone gets back to me, I'll post it on here! (Which seems to be the most common thing here bc last question I asked I waited for an answer for a long time and got 0 response and in the end fixed it myself!) The code is a bit lengthy though...

 private bool moving;
 public float timeBetweenMove;
 private float timeBetweenMoveCounter;
 private Rigidbody2D myRigidbody;

 public float timeToMove;
 private float timeToMoveCounter;

 //public float waitToReload;
 //private GameObject thePlayer;
 private Vector3 moveDirection;
 public float moveSpeed;

 // The target marker.
 public Transform target;
 

 // Speed in units per sec.
 public float speed;

 public GameObject bullet;
 public bool shooting;
 public bool following;

 public float attackTime;
 private float attackTimeCounter;

 private void Start()
 {
     
     following = false;

     myRigidbody = GetComponent<Rigidbody2D>();

     timeBetweenMoveCounter = Random.Range(timeBetweenMove * 0.75f, timeBetweenMove * 1.25f);
     timeToMoveCounter = Random.Range(timeToMove * 0.75f, timeToMove * 1.25f);
 }



 void Update()
 {
     //following movement
     if (following)
     {

         if (moving)
         {
             // The step size is equal to speed times frame time.
             float step = speed * Time.deltaTime;

             // Move enemy position a step closer to the target.
             transform.position = Vector3.MoveTowards(transform.position, target.position, step);

             timeToMoveCounter -= Time.deltaTime;

             if (timeToMoveCounter < 0f)
             {
                 moving = false;
                 //timeBetweenMoveCounter = timeBetweenMove;
                 timeBetweenMoveCounter = Random.Range(timeBetweenMove * 0.25f, timeBetweenMove * 1.25f);
             }
         }


         else
         {
             timeBetweenMoveCounter -= Time.deltaTime;
             myRigidbody.velocity = Vector2.zero;

             if (timeBetweenMoveCounter < 0f)
             {
                 moving = true;
                 //timeToMoveCounter = timeToMove;
                 timeToMoveCounter = Random.Range(timeToMove * 0.25f, timeToMove * 1.25f);
             }
         }
     }

     //regular movement
     else
     {
         if (moving)
         {
             timeToMoveCounter -= Time.deltaTime;
             myRigidbody.velocity = moveDirection;

             if (timeToMoveCounter < 0f)
             {
                 moving = false;
                 //timeBetweenMoveCounter = timeBetweenMove;
                 timeBetweenMoveCounter = Random.Range(timeBetweenMove * 0.75f, timeBetweenMove * 1.25f);
             }
         }


         else
         {
             timeBetweenMoveCounter -= Time.deltaTime;
             myRigidbody.velocity = Vector2.zero;

             if (timeBetweenMoveCounter < 0f)
             {
                 moving = true;
                 //timeToMoveCounter = timeToMove;
                 timeToMoveCounter = Random.Range(timeToMove * 0.75f, timeToMove * 1.25f);

                 moveDirection = new Vector3(Random.Range(-1f, 1f) * moveSpeed, Random.Range(-1f, 1f) * moveSpeed, 0f);
             }
         }
     }


     if (attackTimeCounter >= 0)
     {
         attackTimeCounter -= Time.deltaTime;
     }

     if (attackTimeCounter < 0)
     {
         shooting = false;
     }


     if (shooting)
     {
         shooting = true;
         //attackTimeCounter = attackTime - shootSpeed;
         attackTimeCounter = attackTime;

         Instantiate(bullet);
     }
    
 }

 private void OnTriggerEnter2D(Collider2D other)
 {
     if (other.gameObject.tag == "Player")
     {
         following = true;
         shooting = true;

         
         //GameObject shootTowards = GameObject.FindGameObjectWithTag("Player");
     }
     
 }

 private void OnTriggerExit2D(Collider2D other)
 {
     if (other.gameObject.tag == "Player")
     {
         shooting = false;
         following = false;
     }
 }

}

Where I want the ontriggerenter to also pick the target rather than me assigning the target in unity! Thanks!

Comment
Add comment · Show 1
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 toddisarockstar · Dec 28, 2018 at 12:40 PM 0
Share

i think its wonderfull that you are trying to be part of the community, but i wanted to give reason why your question is not getting answers since you mentioned. generally we do not write your scripts for you. from looking at this post and your script, it seems you are very profficient at setting up colliders and looking for tags. your detailed post leads me to beleive you know how to use a transform variable. what are you not sure how to do? if you give the line that you are stuck on or specific code you dont know how to write, you get quick responces. the purpose of this site is not to save your self time in testing or working out lengthy code. it is here for for people to get specific answers when they dont know how to do something.

for this question i would repost the line that you don't know how to write, or specify the lack of knowledge that is preventing you from finishing your script, and you will get quick answers. this will save everyone time when reading your question.

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by jtok4j · Dec 28, 2018 at 05:12 AM

After a review of your script, it appears to me that your target, is a Transform, with the name target, and referred to once in your script on line: 54 (e.g. target.position)

If you'd like to pick the target, meaning have "target" (the Transform) get it's Transform info from the newly discovered object (other.gameObject.tag == "Player" in OnTriggerEnter2D)... then I'd add this at line: 143

target.transform.position = other.transform.position;

(if your not familiar)The above line of C# code reads: target's position values are now set to the position values of other (other, as found to be in OnTriggerEnter2D)

Hope this helps, let me know if you have any questions.

Comment
Add comment · Show 3 · 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 DoWeLikeTurtles · Dec 29, 2018 at 06:17 PM 0
Share

When I do this, it comes up with an error:

NullReferenceException: Object reference not set to an instance of an object Pathing.Update () (at Assets/Scripts/Pathing.cs:59)

which is on the line:

             transform.position = Vector3.$$anonymous$$oveTowards(transform.position, target.position, step);

I'm having problems where it forces me to assign a target on the "public Transform target;" in unity and displays errors when i don't, meaning that when i switch scenes and the player is "carried over" to the new scene, the enemies in the new scene have no target to go towards because i cannot assign a target transform to something that isnt there! XD while i wouldn't $$anonymous$$d assigning the target manually, I am trying to make a random spawning feature and need to solve this in order to do so because when a enemy spawns it does not have the transform set up! eh, idk! I'll keep messing around to see what I can come up with I guess! Thanks for your help! I hope you can help with this one too!

avatar image Eno-Khaon DoWeLikeTurtles · Dec 29, 2018 at 08:31 PM 1
Share

To remedy the problem with null references, just make sure they're not null before using them:

 if(target != null)
 {
     // move towards target
 }


Since you can't guarantee that they won't be null, double check them ahead of time.

Edit: Also, be certain about what you assign. A class will be passed by reference, but a value will be passed as a copy. Setting the Transform variable is a better choice here, because saving its position to a Vector3 variable will only do so for that exact moment.

 Vector3 va = transform.position;
 Vector3 vb = va;
 va += Vector3.right;
 Debug.Log("va == vb: " + (va == vb)); // false
 
 Transform ta = transform.position;
 Transform tb = ta;
 ta.position += Vector3.right;
 Debug.Log("ta == tb: " + (ta == tb)); // true
avatar image DoWeLikeTurtles · Jan 03, 2019 at 06:07 PM 0
Share

Thanks for all your help! You actually gave me a great idea which solved my problem! I changed my "public Transform target" to "public GameObject target" and then in my //following code ins$$anonymous$$d of transform.position = Vector3.$$anonymous$$oveTowards(transform.position, target.position, step);

I wrote

             transform.position = Vector3.$$anonymous$$oveTowards(transform.position, target.transform.position, step);

to convert it to a gameobject.transform cause it cant implicitly convert that by itself! and then in my ontriggerenter I kept all of it and just added target = other.gameObject; which seems to have assigned the target to my player and seems to be working between scenes and even the random spawns! While I would like to make it so the gameobject goes back to "null" on ontriggerexit, When I add that line then the ontriggerenter doesn't work, which confuses me but thats ok! XD I don't know how efficient this is as I'm relatively new so if theres a way to refine it then by all means please share! I tried what you said and wasn't able to get it to work so I switched things up! though now that I look at your original response I think if I did that and switched the public transform to public gameobject, that may work but I havent tested it yet!

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

113 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 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

OnTriggerExit is not calling 2 Answers

OnTriggerEnter, OnTriggerExit Work Only Once 2 Answers

OnTriggerExit doesn't fire when changing RigidBody (bug? feature?) 2 Answers

OnTrigger bullet with multiple colliders on enemy 1 Answer

Problem using trigger to set gameobjects active 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