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 nonwibb · Nov 05, 2019 at 08:14 PM · classforeachmethod

Can't use method from custom class during foreach

In my program, I created a class, 'Predator' that creates a GameObject and has methods, specifically one to move the object. Here that is:

     public Predator(float speed, float splitsize) {
         this.speed = speed;
         this.splitsize = splitsize;
 
         PredObjPrefab = Resources.Load("Predator") as GameObject; 
         PredObj = GameObject.Instantiate(PredObjPrefab) as GameObject; // Instantiate
         PredFolder = GameObject.Find ("PredFolder"); // Storing Predator in folder to not make a mess
         FoodFolder = GameObject.Find ("FoodFolder");
         PredObj.transform.SetParent (PredFolder.transform);
         rb = PredObj.GetComponent<Rigidbody> ();
     }
     public void Move() {
         // Find closest food to self
         distance = 100000;
         foreach (Transform child in FoodFolder.transform) {
             tempdistance = Vector3.Distance (child.transform.position, PredObj.transform.position);
             if (tempdistance < distance) {
                 ClosestFood = child.gameObject;
                 distance = tempdistance;
             }
         }
         // Move towards food by changing self velocity
         PredObj.transform.LookAt(ClosestFood.transform);
         rb.velocity = speed*PredObj.transform.forward;
     }

Every Predator I spawn is stored in PredFolder, a GameObject. In my main file I have started with just two Predators. I want to access them by iterating through the children of PredFolder. I attempt to do this with a foreach.

     void Start () {
         PredFolder = GameObject.Find ("PredFolder");
         for (i = 0; i < 100; i++) { // Initial food spawn so that the first predators don't starve
             Foodtemp = new Food (new Vector3 (Random.Range (-500, 500), 1, Random.Range (-500, 500)));
 
         }
         catchTime = Time.time + 1; // Time must pass one second before spawning more food
         Predtemp = new Predator (10, 10); // Initial predator (speed, splitsize)
         Predtemp.PredObj.transform.position = new Vector3 (0, 0, 0);
         Predtemp = new Predator (10, 10); // Initial predator (speed, splitsize)
         Predtemp.PredObj.transform.position = new Vector3 (10, 0, 0);
     }
     
     // Update is called once per frame
     void Update () {
         if (Time.time >= catchTime) { // Spawn food every second
             Foodtemp = new Food (new Vector3 (Random.Range (-500, 500), 1, Random.Range (-500, 500)));
             catchTime = Time.time + 1;
         }
         foreach (Transform child in PredFolder.transform) {
             child.Move ();
         }
     }

The last statement is clearly not working because child is a Transform, which wouldn't have the method Move() from my Predator class. I can't figure out how to change the parameters of the foreach so that each child is a Predator. How do I properly execute methods of each Predator in the folder?

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
0

Answer by Casiell · Nov 06, 2019 at 10:54 AM

So first of all if your Predator class doesn't inherit from MonoBehavior, your approach won't work. If it does, I would still call this a bad approach.

Why rely on hierarchy when you can just store all your Predator objects in a list and iterate it?

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
avatar image
0

Answer by xxmariofer · Nov 06, 2019 at 11:57 AM

 foreach (Transform child in PredFolder.transform) {
   child.GetComponent<Predator>().Move(); 
 }

Comment
Add comment · Show 2 · 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 Casiell · Nov 06, 2019 at 12:16 PM 0
Share

The problem with this is that Predator is not a $$anonymous$$onoBehavior so it's not attached to gameobjects, so you can't access it with GetComponent.

avatar image xxmariofer Casiell · Nov 06, 2019 at 12:27 PM 0
Share

true, i was reading too fast and didnt realize he was using constructors, then his issue is with oop and c#, probably doesnt know that both predators that he has created are already GC before reaching the update, because he is not saving them anywhere

 List<Predator> predatorList = new List<Predator>();
 
 void Awake(){
    predatorList.Add(new Predator (10, 10));
    predatorList[0].PredObj.transform.position = new Vector3 (0, 0, 0);
    predatorList.Add(new Predator (10, 10));
    predatorList[1].PredObj.transform.position = new Vector3 (0, 0, 0);
 }

 void Update(){
      foreach (Predator predator in predatorList) {
          predator.$$anonymous$$ove ();
      }
  }



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

118 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 avatar image avatar image avatar image avatar image avatar image

Related Questions

Trying to run 5 instances of a static method at once to do an action, probably a dumb thing to do? 0 Answers

Why the variable don't change your value? 1 Answer

Accessing a method / void from another class? 0 Answers

Passing a class instance to a method 1 Answer

Call method from attached Gameobject 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