Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

How to get attributes of a gameObject from 2 script components of the same name?

Discussion in 'Scripting' started by AlmantusK, Mar 20, 2016.

  1. AlmantusK

    AlmantusK

    Joined:
    Oct 7, 2015
    Posts:
    30
    I have a class called HandController. It controls the hand based on mouse movements. When I hold LMB, it moves left hand, when I press RMB, it moves right hand. The movements are different, but it differs only by values, not by actual functionality, thus there's no point to write two different scripts with different names. So I have two components of the same name. The problem is, that I want to get a variable in another script from HandController (the variable I want to get is isHandMoving). How am I supposed to do it, when I have a duplicate component?
     
  2. gorbit99

    gorbit99

    Joined:
    Jul 14, 2015
    Posts:
    1,350
    Give them an attribute called "hand" where you specify, which hand it controlls, then
    var hc = GetComponents<HandController>();
    for (int n = 0; n < hc.Length; n++) {
    if (hc[n].hand == "left") {
    //DO stuff
    }
    }
     
    AlmantusK likes this.
  3. AlmantusK

    AlmantusK

    Joined:
    Oct 7, 2015
    Posts:
    30
    Thank you, a good and fast solution:)