Search Unity

Assign Script via revealed

Discussion in 'Scripting' started by kwabbott, Dec 10, 2007.

  1. kwabbott

    kwabbott

    Joined:
    Jun 5, 2007
    Posts:
    151
    I'm trying to create a script to attach to a button or switch. that would allow me to assign an object to affect and a script to execute.

    For example, if I wanted my button to cause a door to open I'd like simply be able to drop the door gameobject and open script onto revealed variable slots.

    Here's what I tried for the script that would be attached to the button, in the hopes that I could just drop the script onto the Component variable (not sure if this really exists in the way I hope).

    Code (csharp):
    1.  
    2. var receiver : GameObject;
    3. var script : Component;
    4.  
    5. function OnMouseDown () {
    6.     receiver.AddComponent(script);
    7. }
    8.  
    I also tried attaching the script I want to a GameObject but I couldn't figure out how to access the script without using it's name. In the code below where the questions marks are - how do I get it to take the only script attached to the gameobject?



    Code (csharp):
    1.  
    2. var receiver : GameObject;
    3. var scriptHolder : GameObject;
    4.  
    5. function OnMouseDown () {
    6. var theScript = scriptHolder.GetComponent(????);
    7.     receiver.AddComponent(theScript);
    8. }
    9.  
    I hope this makes sense.

    thanks

    Kevin[/code]
     
  2. Bampf

    Bampf

    Joined:
    Oct 21, 2005
    Posts:
    369
    You might be able to use FindObjectOfType to do what you want. But to do so you'd have to see variables of type "Type" in the inspector, not sure that's possible.

    Easy solution is to have the button send a particular message (expressed as a string) to the object in question. One or all of the object's scripts can respond to this message.

    http://unity3d.com/support/documentation/ScriptReference/Component.SendMessage.html

    So instead of dragging the script of interest to the button, you'd have a string you'd set and/or a value. Those would be used as the arguments to SendMessage.