Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 Corinator3000 · Mar 30, 2015 at 08:18 AM · gameobjectloopforeachmagnet

foreach Gameobject in array problems

I am making a script for magnetism. I have an electromagnet and two metal cubes. I want all of the cubes to attract to the electromagnet. Here is my script:

 using UnityEngine;
 using System.Collections;
 
 public class eMag : MonoBehaviour {
 
     private float xMagnitude;
     private float yMagnitude;
     private float zMagnitude;
     [Range(-50,50)]
     public float magneticForce = 1;
 
     // Use this for initialization
     void Start () {
 
     }
     
     // Update is called once per frame
     void Update () {
         GameObject[] magnets = GameObject.FindGameObjectsWithTag("Magnetic");
         foreach(GameObject magnet in magnets)
         {
             xMagnitude = (GameObject.FindWithTag("Electromagnet").transform.position.x - GameObject.FindWithTag("Magnetic").transform.position.x) * magneticForce;
             yMagnitude = (GameObject.FindWithTag("Electromagnet").transform.position.y - GameObject.FindWithTag("Magnetic").transform.position.y) * magneticForce;
             zMagnitude = (GameObject.FindWithTag("Electromagnet").transform.position.z - GameObject.FindWithTag("Magnetic").transform.position.z) * magneticForce;
             GameObject.FindWithTag("Magnetic").GetComponent<Rigidbody>().AddForce(xMagnitude,yMagnitude,zMagnitude);
         }
     }
 }

The electromagnet is tagged as "Electromagnet" and the metal cubes are tagged as "Magnetic".

This works flawlessly, however it only works for one cube. I can't figure out why the foreach loop is not looping for all cubes labeled "Magnetic". My apologies for being relatively new to C# and not knowing how to use the foreach loop function.

Thank you for your consideration.

Comment
Add comment · Show 2
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 AlwaysSunny · Mar 30, 2015 at 03:15 AM 2
Share

You should avoid using GameObject.Find or related methods wherever possible. You are also using it improperly; there's no reason to use the function here at all, let alone 8 times.

Use Physics.OverlapSphere on your magnetized objects to discover all nearby objects. Check for some property like their tag. To objects with the proper tag, apply force scaled by distance to achieve faux magnetism. Also, there's no reason to split the force vector into its components.

avatar image fafase · Mar 30, 2015 at 08:24 AM 0
Share

Your issue is not in Unity but in your knowledge of C# and how to use foreach loop.

1 Reply

· Add your reply
  • Sort: 
avatar image
2

Answer by Hrungdak · Mar 30, 2015 at 08:34 AM

Your loop iterates ovver each GameObject with Tag "Magnetic". The problem lies within the loop.

In the loop you use three times (GameObject.FindWithTag("Electromagnet"). I think you have only one such elektromagnet in your game? If this is true, cache this object first:

 private Transform m_ElectroMagnet;
 
 void Start () {
     m_ElectroMagnet = GameObject.FindWithTag("Electromagnet").Transform;
 }

The second problem is, that GameObject.FindWithTag("Magnetic") always finds the same object with this Tag in the Hierarchy. You have already searched all objects with this tag, before the loop starts. So do something like this:

 void Update () {
 GameObject[] magnets = GameObject.FindGameObjectsWithTag("Magnetic");
 foreach(GameObject magnet in magnets)
 {
 xMagnitude = m_ElectroMagnet.position.x - magnet.transform.position.x) * magneticForce;
 yMagnitude = m_ElectroMagnet.position.y - magnet.transform.position.y) * magneticForce;
 zMagnitude = m_ElectroMagnet.position.z - magnet.transform.position.z) * magneticForce;
 magnet.GetComponent<Rigidbody>().AddForce(xMagnitude,yMagnitude,zMagnitude);
 }
 }
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

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Can I play multiple AudioSources from one gameobject? 8 Answers

how to use two foreach loops into another correctly 1 Answer

foreach loop problem 1 Answer

instantiate in foreach loop only gives last string in list 2 Answers

multiple targeting 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