Search Unity

Problem with GetComponent

Discussion in 'Scripting' started by DarkSoul, May 19, 2010.

  1. DarkSoul

    DarkSoul

    Joined:
    Dec 24, 2009
    Posts:
    37
    Hello.
    I want change a variable inside a script from other script, the code is:
    Code (csharp):
    1. Laser1 ns = gameObject.GetComponent<Laser1>();
    2. ns.ShootDirection = EnemyPosition;
    I follow the example in the help, but the code returns me this error:
    NullReferenceException: Object reference not set to an instance of an object. The console tells me that error is in:
    Code (csharp):
    1. Laser1 ns = gameObject.GetComponent<Laser1>();
    The variables are public, where is the problem?
     
  2. Tempest

    Tempest

    Joined:
    Dec 10, 2008
    Posts:
    1,286
    Is the accessing script, and the target script, on the gameObject?
     
  3. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    I guess you have no Laser1 component attached to the game object.

    --Eric
     
  4. DarkSoul

    DarkSoul

    Joined:
    Dec 24, 2009
    Posts:
    37
    The "Laser1.cs" is in a gameObject, but I want change a vector3 in "Laser1.cs" from other script (with name "AI_Turret.cs").

    The Vector3 in Laser1.cs is:
    Code (csharp):
    1. public Vector3 ShootDirection = Vector3.zero;
    The part of code in the AI_Turret.cs is:
    Code (csharp):
    1. Laser1 ns = gameObject.GetComponent<Laser1>();
    2. ns.ShootDirection = EnemyPosition;
    Do I have to do anything else? I don't know where is the problem.
     
  5. capanno

    capanno

    Joined:
    Feb 19, 2010
    Posts:
    65
    Im also interested in this problem! Im also getting this error.
     
  6. Dreamora

    Dreamora

    Joined:
    Apr 5, 2008
    Posts:
    26,601
    if it is in a gameobject is not of interest.
    GetComponent will only get components on the CURRENT game object :)
    if you want it from another game object you must use FindObject(s)OfType
     
  7. DarkSoul

    DarkSoul

    Joined:
    Dec 24, 2009
    Posts:
    37
    I solved the problem. The problem was with Visual Studio, the synchronization between Unity and Visual Studio was broken.
    But thanks for all!