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

[C#] How do I disable a component from a different object (in script)?

Discussion in 'Scripting' started by IAmZeph, Feb 5, 2015.

  1. IAmZeph

    IAmZeph

    Joined:
    Feb 5, 2015
    Posts:
    7
    Hello! I have a script where I can switch between diferent characters.

    This is on the first character: http://pastebin.com/HTkBjMUE
    This is on the second character: http://pastebin.com/eP4NTFgW
    This is on the third character: http://pastebin.com/a6xwTa72

    I want it so that when I switch to use the first character the second ones and the third ones characterController script is turned off. How do I do that? Like GetComponent<characterController>().enabled = false; only for components on another game object.

    I'm a new scripter so sorry for any mistakes.

    - Daniel :)
     
  2. twobob

    twobob

    Joined:
    Jun 28, 2014
    Posts:
    2,058
    you could keep a list of the objects and disable all the others.
    List<characterController> cList = new List<characterController>();
    cList.Add(Thing);

    or you could setup a method that you "Send" to on the others that disables them.

    The first one is tidier IMHO but since you only have a few things to manage perhaps the second.
    There are a bunch of other ways too...
     
  3. IAmZeph

    IAmZeph

    Joined:
    Feb 5, 2015
    Posts:
    7
    Thank you a lot! :)
    I wanted to use your way but I found out that you can do this - http://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html.

    This is my new code for anybody that wants to see it - http://pastebin.com/YcdVA3Uu
    Thanks anyway!

    - Daniel
     
  4. twobob

    twobob

    Joined:
    Jun 28, 2014
    Posts:
    2,058
    Err yeah.

    That is going to be about the slowest way imaginable to do that. (okay, quite slow)

    But it will work :)

    (It is quicker to cache a single reference to the controller and then reference the .enabled property, your way is going to look that thing up every single time you ask for the value. Slooooow)

    A list of these cached properties, correctly iterated over should be pretty nippy.
    Given how miniscule the work is that this code does should not matter....

    Until you do it every frame, and hang a MMORPG on top of it, then you will be looking to remove such pointless work as this.

    Hope it helps.
     
    Last edited: Feb 7, 2015