- Home /
The question is answered, right answer was accepted
Instantiated Prefab using its transform and object on other scripts
So my problem is that on my other object i cannot select a gameobject to be the object selected in another script: i checked the other script and the problem is here:
void Start ()
{
gameManager GM = GameManagerObj.GetComponent<gameManager>();
PlayerObj = GM.PlayerStats;
stats = PlayerObj.GetComponent<PlayerStats>();
}
It does not assign PlayerObj with the values of the PlayerStats found in gameManager script.
ins$$anonymous$$d of trying that I also tryed this:
PlayerObj = GameObject.FindGameObjectWithTag("Player");
stats = PlayerObj.GetComponent<PlayerStats>();
I got same error of null reference on PlayerObj.
also by trying to find it by name returns the same null reference error: PlayerObj = GameObject.Find("SorcererCls(Clone)"); stats = PlayerObj.GetComponent();
I can't think of anything else if your gameobject is in your hierarchy and not being dynamically created when the script tries to find it or perhaps after creating the tag you forgot to set it on the gameobject. try finding the gameobject by gameobject.find just to see if its being referenced ...
If the object is dynamically created make sure that you are trying to access it with gameobject.findwithtag after it is being created in the hierarchy. I dont know your code structure and how your script sequence work. So follow your logic and enable the code after the instance of its creation ...
Aren't you instantiating your enemies for spawning them ? when they are being spawned you can trigger this piece of code for finding with tag
Answer by dbrizov · Jul 30, 2014 at 12:57 PM
If you want to use the GameManager in the second script and take a reference to it in the Start() method, you need to be sure that every single reference in the GameManager script is instantiated. You should ask yourself: "Is the GameManager script ready to use? If so, then you should take a reference to it". A solution is to Instantiate the GameManager in it's Awake() method, and take it as a component in the Start() method in the second script.
if i use getcomponent on start i cant use the statsscript.exp
never$$anonymous$$d i forgot to make that public and put it on top but still this says i have an unasigned reference here :
GameObject InstantiatePlayer = Instantiate(PlayerPrefab,SpawnPosition.transform.position,SpawnPosition.transform.rotation) as GameObject;
PlayerTrans = InstantiatePlayer.gameObject.transform;
PlayerStats = InstantiatePlayer.gameObject;
i just seen that in the inspector on game$$anonymous$$anager script PlayerStats did select the right object but it still says error: here that it was not assigned void Start () { Health = 100; game$$anonymous$$anager G$$anonymous$$ = Game$$anonymous$$anagerObj.GetComponent(); PlayerObj = G$$anonymous$$.PlayerStats.gameObject; stats = PlayerObj.GetComponent(); }