Search Unity

Acessing an object remotely? (In an odd way)

Discussion in 'Scripting' started by Sam_Pr, Jul 27, 2013.

  1. Sam_Pr

    Sam_Pr

    Joined:
    Aug 23, 2012
    Posts:
    66
    I want to make a script that will raycast and if that raycast hits a game object tagged with "Tree" it will then take the object named tree and use addcomponent to add a script to the tree.

    Any ideas on how I would go about doing this? Thanks for answering, and if you need any more detail just ask me!
     
  2. wolvz38

    wolvz38

    Joined:
    Feb 6, 2013
    Posts:
    66
    I just put this together real quick but it should do what your wanting... next time you can just look here: http://docs.unity3d.com/Documentation/ScriptReference/Physics.Raycast.html

    Code (csharp):
    1.     function Update () {
    2.         var hit : RaycastHit;
    3.         var fwd = transform.TransformDirection (Vector3.forward);
    4.         if (Physics.Raycast (transform.position, fwd, hit, 100)) {
    5.             var myScript : TestScript;
    6.             myScript = hit.transform.GetComponent(TestScript);
    7.             if(hit.transform.tag == "Tree"  myScript == null) {
    8.                 hit.transform.gameObject.AddComponent("TestScript");
    9.             }
    10.         }
    11.     }
     
  3. Sam_Pr

    Sam_Pr

    Joined:
    Aug 23, 2012
    Posts:
    66
    Awesome, thanks a ton!
     
  4. wolvz38

    wolvz38

    Joined:
    Feb 6, 2013
    Posts:
    66
    Yeah no problem. Also remember that if you want to change how far forward the raycast will go you need to change the 100 to whatever distance you want.
     
  5. Sam_Pr

    Sam_Pr

    Joined:
    Aug 23, 2012
    Posts:
    66
    Yes, of course