Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How do I move multiple prefabs at the same time through scripts?

Discussion in 'Prefabs' started by Mirdov, Oct 18, 2019.

  1. Mirdov

    Mirdov

    Joined:
    Apr 19, 2017
    Posts:
    5
    So what's up, I have a prefab in the script scene and every time I click the button it moves exactly as I want it!
    But if I put more prefab in the scene just the last prefab placed moves and I want everyone to move at the same time, it's been over 2 days and I don't find anything on the internet about it, and just missing that to finish my mechanics game and I don't know what to try anymore!
    Every help is welcome!

    I'm using this script code in prefab (GameObject):

    Code (CSharp):
    1.  
    2. public static bool moveSabonete;
    3.  
    4. public void Update()
    5.     {
    6.         if(moveSabonete)
    7.         {
    8.             MoveSaboneteVoid(2f);
    9.         }
    10.     }
    11.     public void MoveSaboneteVoid(float m)
    12.     {    
    13.         var pos = this.transform.position;
    14.         pos.y -= 2f;
    15.         this.transform.position = pos;
    16.  
    17.         moveSabonete = false;
    18.     }
    And this script on the button:

    Code (CSharp):
    1. public void MoveButton()
    2. {
    3.       SaboneteScript.moveSabonete = true;
    4. }
     
  2. hjohnsen

    hjohnsen

    Joined:
    Feb 4, 2018
    Posts:
    67
    The title of your post is misleading.

    How do you get the reference of you SaboneteScript ?

    If you want to update the position of all your objects than you need to set the boolean on all objects, not the first or the last one (or you could put all of them in a hierarchy and move that hierarchy instead of all your prefabs).
     
  3. Mirdov

    Mirdov

    Joined:
    Apr 19, 2017
    Posts:
    5
    I didn't understand why the misleading title?

    But when I set the variable to true, doesn't it have to change all prefabs?
    If I put the line:
    Code (CSharp):
    1. if(!moveSabonete)
    2. {
    3.      MoveSabonteVoid(2f);
    4. }

    it works, only it moves all infinitely, the moment I change it to true again!
     
  4. hjohnsen

    hjohnsen

    Joined:
    Feb 4, 2018
    Posts:
    67
    The Update() function is executed on each instance of your prefab.
    moveSabonete is a global variable that your are setting to false, so it will be false after the first prefab executes it's Update() function. Don't resert the moveSabonete in the update code but do it in your game manager.
     
  5. Mirdov

    Mirdov

    Joined:
    Apr 19, 2017
    Posts:
    5
    would you have a link? where can i do this from?
    I tried to implement what I said more got a lot more confusing than before and it's not working!