Search Unity

OnMouseDown - sending object name to another script problem c#

Discussion in 'Scripting' started by Dazz500, Dec 22, 2014.

  1. Dazz500

    Dazz500

    Joined:
    Nov 13, 2014
    Posts:
    64
    Hi all,

    I have a gameobject called plane and I've got a script that instantiates 10 clones, they get a number added to the end of them so they all have a unique gameobject name, so I end up with 11 gameobjects which are : plane ( original ) and the clones are named plane0, plane1 etc.

    I have a script called playerscript attached to plane and all the plane clones.

    I have another gameobject called Tower with a script called Controller attached to it.

    What I want to do is, when I click on a plane I want the variable "idtext" ( which is in the Controller script ) to contain the gameobject name of the object I just clicked on.
    What actually happens is if I click on the original plane idtext does equal the name "plane" as it should BUT when I click on a clone idtext doesn't equal anything.
    The debug.log shows the proper gameobject name in the console if I click on a clone but this just isn't getting transferred to the idtext variable for some reason.

    Each clone has a Box collider & a Rigidbody
    Note : I have dragged gameobject Tower to Target in the inspector.





    Code (csharp):
    1.  
    2. public Transform target;
    3.  
    4.  
    5. void OnMouseDown(){
    6.         // this object was clicked - do something
    7.        
    8.         Controller targetScript = target.GetComponent<Controller>();
    9.          a = gameObject.name;
    10.         targetScript.idtext = gameObject.name  ;  // this works with original but not a clone
    11.        
    12.  Debug.Log (" plane clicked is  " +  a);
    13.  
    14.  
    15.  
    16. }
    17.  
    18.  

    Any help is appreciated - thanks.
     
  2. renman3000

    renman3000

    Joined:
    Nov 7, 2011
    Posts:
    6,697
    a is always the owner of the script.

    To get differnt planes, you need to use a raycast, hit.

    Make sure you have one controller that fires the ray, not each of the clones each using an input.
     
    Last edited: Dec 22, 2014
  3. Dazz500

    Dazz500

    Joined:
    Nov 13, 2014
    Posts:
    64
    If a is always the owner of the script why does my Debug.Log show the correct clone in the console ( i.e plane4 )
     
  4. CodeMonke234

    CodeMonke234

    Joined:
    Oct 13, 2010
    Posts:
    181
    The general approach should work

    target is probably not being set in clone properly - you could probably check this by adding debug.log and printing it out first.

    A slightly different approach might be to set each objects controller variable in awake and get it via a tag....
    This has the benefit of only making call once and u can be sure it is set