Solved
GetComponentInChildren not working , why ?
Hi, my script doesn't works and i don't know why the "GetComponentInChildren" don't work; this is my first script :
public class PlayerFeatures : MonoBehaviour
{
public GunShooting GunShootingClass;
void Awake ()
{
GunShootingClass = GetComponent<GunShooting>();
GunShootingClass.CreateGun();
}
}
who calls the second script :
public class GunShooting : MonoBehaviour
{
public void CreateGun()
{
Debug.Log("Creating gun !");
}
}
My second script is into a children of the first script; the error is : NullReferenceException : Object reference not set to an nstance of an object in "Player Features" on the line : GunShootingClass.CreateGun();
Best Regards
Answer by kaplica · Dec 14, 2017 at 10:12 PM
You are trying to get class of type GunShooting and then get component of that class? Classes are components. You access components (classes) from game objects. Game objects are the base entities in unity3d that derive from object, and components can be added on to those game objects to define behaviour.
This is a sample:
public GameObject GunShootingGo;
private GunShooting _gunShooting;
void Awake()
{
_gunShooting = GunShootingGo.GetComponent<GunShooting>();
}
Answer by MaxGuernseyIII · Dec 14, 2017 at 10:15 PM
Your script does not appear to actually be calling GetComponentInChildren. It calls GetComponent.
Answer by slayce · Dec 15, 2017 at 08:36 AM
I tried your answer kaplica, then, i put une gameobject in the inspector, then i launch the game, and unity tells me that i don't put a gameobject in the inspector, but it has !
Ok it's solved, i just shut down unity and launch it again
Follow this Question
Related Questions
error CS0201 1 Answer
Unity 5 doesn't detect some positions in Vector3 0 Answers
The Built [exe] of my game won't go past Splash Screen 0 Answers
Visual Studio 2015 keeps crashing... 1 Answer