Unity3D - GameObject.Find() returning null for disabled object [duplicate] - unity3d

This question already has answers here:
How to find inactive objects using GameObject.Find(" ") in Unity3D?
(7 answers)
Closed 5 years ago.
I have a game object that at the beginning of the game is disabled. Then I want to enable it later via script. So far I have tried to use the following code:
GameObject.Find("name").SetActive (true);
The problem is that as the game object at the beginning is disabled when I do
GameObject.Find("name")
I get null. So I don't know how to activate it. It's a canvas.

You can create a class variable in your script, and then in the Unity scene editor assign your disabled object to that class variable.
For example:
In your script file, create the class variable:
public GameObject objectToEnable;
Then, in the scene editor, the "objectToEnable" variable will appear on the Script component of the object containing your script. Simply drag your disabled object to that variable (in the scene editor) to set the reference.
Once you do that, at runtime you can just do:
objectToEnable.SetActive(true);
The reference should still be valid, even if the object is disabled.

You could first save the object in a variable, for example you first declare a variable that will hold the object
GameObject tempVar; //this line goes outside any function, not in Start or Update
Then in the Start or Awake function you find the object and save it
tempVar = GameObject.Find("name"); // this line goes in Start, just before you disable the object
tempVar.SetActive(false); //now the object is disabled but saved in a variable with which you can access it at any time
Of course, this code assumes the object is NOT disabled before the game starts.

Related

Get position of GameObject from script in it or in other GameObject

In Unity AR Fundation
In a project, once you have selected a point on the screen, I generate a plane and create objects on it. Once the plan is created, how do I get its position from another script so that I can generate the items there?
Or how can I get his position on a script in the plan?
Well, in order to get a position from an object, you need a reference to it. You can acquire it in several ways.
Here are some options:
Using FindObjectOfType (assuming your plane has some kind of a unique script attached or it's assigned on a variable that is attached to that script you're looking for)
Using GameObject.Find which will look for for an object that matches a specific name
Using a static field which can be accessed from anywhere (upon creating your plane, you'll have to assign it to a static field)
When it comes to accessing the position of a GameObject you can do that in the following way:
yourGameObject.transform.position

Cannot get the child of a GameObject through script [duplicate]

This question already has answers here:
How to find child of a GameObject or the script attached to child GameObject via script
(4 answers)
Closed 4 years ago.
I want to access the animator component of my player character. The character is spawned under the GameObject Character position, which it self is the child of Game Manager.
The character prefabs have various names, so I cannot find them through exact name. So its easier to just get the only child of Character position.
Game Manager
Character position
Player Prefab
Ive searched online and tried GetChild by index and GetComponentInChildren. None of them work. Below is the script I wrote for this:
private Animator archerAnimator;
private float startSpeed;
GameObject charPos;
GameObject archer_;
// Use this for initialization
void Start () {
charPos = GameObject.Find("Game manager/Character position");
Debug.Log(charPos);
archer_ = charPos.transform.GetChild(0).gameObject;
archerAnimator = charPos.GetComponentInChildren<Animator>();
Debug.Log(archerAnimator);
}
charPos is found, but for archer_ I get the error, Transform child out of bounds. The player archer is not there but is spawned at run time when the scene starts, is this the reason it cannot find it so quickly?
Some guidance would be appreciated.
Thank you
I think you're scanning for the player too early. You should reverse your discovery logic. Instead of scanning for the player and its Animator, you should put a script on the player itself that runs after it is created and reports itself to the game manager or whatever object needs access to it, something like this:
void Start() { GetComponentInParent<GameManager>().OnPlayerSpawned(this); }
I'll also mention that some script finding an object by name and accessing its components is a generally bad idea. Here's a design guideline to always keep in mind: You should traverse Unity's object hierarchy as infrequently as possible, and even if you do, you should only traverse objects that don't have other scripts attached. In this case, you should also put the logic to control the Animator inside your Player script. Then, you wouldn't need to get a reference to the Animator in the first place.

how to change variables in script attached to a prefab through script at runtime?

I have instantiated a prefab in the scene that gets destroyed after 2 secs. I want to change its speed variable in its move script so that whenever it instantiate it has new speed.
The instantiate function returns the game object you created.
GameObject prefabObject = Instantiate(...);
Then you can obviously do something like
prefabObject.GetComponent<moveScript>().speed = 4;
You have not provided enough information, but I will try to answer.
Will this be done by another script or the Move script you have attached on the prefab?
If from the Move script then:
private void Awake()
{
speed = MY_NEW_SPEED;
}
If from another script, then you first need to access the instantiated object and then its Move scripts. You have not provided enough information so I will assume you already have a reference to your instantiated object:
instantiatedObject.GetComponent<Move>().speed = MY_NEW_SPEED;
https://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html

Is there any way to use AddComponent with a script in Unity if there is no instance of that script in the game yet?

I need a way to add a script to an object that I just Instantiated. Ideally I could just set the script to add in the inspector. The problem is that I can't use
public Component scriptToAdd;
because then I would need to already have an empty object or something with the script on it. While that would work it feels kind of dirty or hackish to make an empty that just stores references to something. Also the point of doing it like this for me is to make it more efficient to swap out different scripts. If I had to swap out a script on an empty and then drag the new one in I'd lose on some of that efficiency I'm after. Thanks for any help.
After you instantiate, you should use the GameObject.AddComponent() Class, to add any component Type you want.
for example, if you want to add a camera to the scene.
void Start () {
GameObject myNewCamera = new GameObject();
//creates an empty game object, you can already attach components to it.
myNewCamera.AddComponent<Camera>();
//adds a component of type Camera
}
You can also use the overloaded constructor
GameObject myNewCamera = new GameObject("my object name", typeof(ScriptToAdd));
GameObject myNewCamera = new GameObject("my object name", typeof(ScriptToAdd), typeof(MoreComponentsToAdd));
Also, you should never be afraid of using an empty GameObject on your scene, for keeping information, references, variable values, saves, or anything really. It doesn't really affect the performance of your game, and you can make your life easy just by having an easy to find tag, such as "Engine".
Then you can access anything just by adding:
GameObject.FindGameObjectWithTag("Engine");
I hope I was able to help you :)
-Noe

Should I use Start or Update to call the given method in Unity3d

1.I have a class in which I have a method called ProjectileMotion() with return type IEnumerator and this method is being called from Start().
2. The above script is attached to a prefab that is instantiated from another class.
Problem:
In IENumerator ProjectileMotion() method, I need to have updated position of an object which is moving continuously,so I declared
//assigned the o=gameobject to it and it is moving continuously
Public Transform Target;
In ProjectileMotion(), if I do Target.transform,position, it gives the starting position only and not where it was at the time of instantiation of the prefab to which this script is attached, However, I am able to get the updated position of Target in Update method(checked using Debug.Log).
But I can not call the ProjectileMotion() in Update method of course, what should I do to get updated position of Target every time the prefab is instantiated and so the script is called.
Simply put ...
If you want the code to execute when the component is "started" then call it on start.
OR
If you want the code to execute each frame after the component has started then call it on update.
Judging by the name of this method I would think this is something that updates the position of a projectile after a gun has instantiated it.
The position being updated is likely a per frame operation so.
I would put this in the update method.
EDIT:
UNLESS ...
Does this function do a multiframe animation?
Unity has the concept of coroutines that allow to do certain actions of several frames. in this case you might be better off doing something like this in your start method ...
StartCoroutine(ProjectileMotion)