- Home /
Can I use GetComponents reference outside Of awake and start functions
hello I have a door on other object When user hit "F" door should open and it is opening but when i use reference outside the beginning functions(awake or start) it dosent work how can I fix it ? Door's name is door123 CODE :
Dooropen.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Dooropen : MonoBehaviour {
bool yesintrigger;
door123script d123;
private void Awake()
{
d123 = GameObject.Find("door123").GetComponent<door123script>();
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
yesintrigger = true;
}
}
private void Update()
{
if (yesintrigger)
{
if (Input.GetKeyDown(KeyCode.F))
{
d123.open = true;
}
}
}
}
door123script.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class door123script : MonoBehaviour {
public bool open;
private void Update()
{
if(open)
{
gameObject.SetActive(false);
}
}
}
You can use GetComponent on you want, but iside of any function, why you need? your script should works fine, what do you need change?
private void Update()
{
if (yesintrigger)
{
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.F))
{
d123 = GameObject.Find("door123").GetComponent<door123script>();
d123.open = true;
}
}
}
no It don't works it only works in awake function
Im 100% sure it works, you recive any error? set d123 to public, " public door123script d123;" and add this line.
private void Update()
{
if (yesintrigger)
{
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.F))
{
print(GameObject.Find("door123").gameObject.name);
d123 = GameObject.Find("door123").GetComponent<door123script>();
d123.open = true;
}
}
}
What happend?
On your door script
if(open)
{
gameObject.SetActive(false);
}
if the object is not active, you cant found with GameObject.Find()
Answer by Cuttlas-U · Aug 14, 2017 at 04:44 PM
hi;
try to find the Script by the type and not object name ;
GameObject.FindObjectOfType<door123script>();
I don't see any problems in your code; if u cant use it outside the awake function then there must be something happening when the game start,
maybe u change the door obejct name so it cant find it or any thing else ;