Initializing a prefab's instance's variable - c#

So I'm currently spawning a instance of a prefab GameObject, and I want to initialize some of its variables. Usually I would use FindObjectOfType, however the objects I want to attach to it don't have a type, and are pretty much just empty GameObjects with a few children. I feel like the answer should be incredibly obvious, but I can't wrap my head around a solution. Any help would be greatly appreciated.
Edit: I forgot to mention that the GameObjects I want to apply to the instance's variables are inactive at the time I want to do so.

If you are instantiating the object then wanting to set the variables, then just spawn the object and grab the reference.
YourScriptHere tmp = Instantiate(yourObject).GetComponent<YourScriptHere>();
tmp.SetTheFieldHereEqualTo = someValue;
If you do not want to just set references to an object you are spawning, can you clarify your question a bit?

Sorry if my question wasn't super clear, but I managed to find a solution. I basically put the objects I want to set as the variables in parent object which is always active, then through the script I get the parent object, and finally I get its first child, which would be the object I wanted in the first place:
GameObject variable;
GameObject variableParent;
private void Start()
{
variableParent = GameObject.Find("variableParentName");
variable = variableParent.transform.GetChild(0).gameObject;
}

Related

I find a way to use less "GameObject.find" but I´ve never see somebody do it like that, am I wrong?

I needed to find a better way to find my Game Objects without using GameObject.Find because I have this line more than 30 time is one script, so I created this line on my script:
public List<GameObject> gameObjectList = new List<GameObject>();
Then, I go in the inspector and add manually the gameobjects in the list.
and everything works fine.
But I see nobody talking about that way on internet, so is there something wrong with that way?
Assigning Object references using the Inspector is a great practice! It can make your components more flexible, because you can rewire the same code to work with different Objects.
Note that you can also expose private fields using the SerializeField attribute. Making fields private when you can is good practice, because limiting access to them can help reduce bugs.
Another things to note is that you can also edit Component type fields using the Inspector, so you don't need to do any GetComponent calls in your code. You rarely need to work with GameObjects directly; basically only when you want to destroy a GameObject or modify it's active state.
[SerializeField]
private Button[] buttons = new Button[0];

Unity Array and Instatiation

Im new in unity and I have a problem regarding arrays.
I want to be able to set the Elements of the arrays via script.
Here straight is a "public gridElementScript[] straight;"
If I'm understanding correctly, you're asking how to access Straight from another instance. If so, you need to cast your instantiated prefab to a GameObject and call GetComponent<MyComponent>() on it. Something like I've written below should work for you.
GameObject object = (GameObject)Object.Instantiate(myPrefab)
GridElementScript script = object.GetComponent<GridElementScript>();
script.Straight[0] = neighbor

Unity Script with an Update Function attached to multiple Objects

//GUI Function
private void Update()
{
healthMeterPos.position = WorldToGuiPoint(new Vector2(position.xPos,position.yPos));
}
This is my Update Function which is in a Parent class from which all my gameobjects inherit problem though is that it's only updating the Position for the first GameObject not all of them. Anybody know why?
When you write healthMeteorPos.position = ..., unless healthMeteorPos is either public or [SerializeField] and set uniquely to each one of the objects separatedly, all the object basically execute the same command over the same target which is one object healthMeteorPos.
If you post a little more code we could help more, but generally speaking, if you want every object to affect itself, use transform.position instead of assigning the position of another shared object.

Unity c# - NullReferenceException: Object reference not set to an instance of an object

Im having an error during runtime with my image and text. I have both objects created in my hierarchy named correctly but apparently my script cant find them. Why isn't what i have written not sufficient? All i get in the error is Object reference not set to an instance of an object, but i don't understand why i need to create an instance of this object when i have one in my hierarchy.
I'm still relatively new to both unity and c# and couldn't find any real explanatory answer by searching and the unity tutorials weren't very helpful since I'm sure its just a basic question about c#
private Text serverInfoText;
private GameObject serverInfoImage;
void Awake()
{
serverInfoImage = GameObject.Find ("ServerInfoImage");
serverInfoImage.SetActive (false);
serverInfoText = GameObject.Find("ServerInfoText").GetComponent<Text>();
}
Impossible to say without looking at your scene.
Things to try:
GameObject.Find only works on active game objects. Make sure the game objects are not greyed out in your scene view.
Double check the name strings are correct and use Debug.Log to sanity check.
You don't mention which line the actual exception occurs. In your above code, it's possible to throw an exception in two locations: on SetActive() if serverInfoImage is null, or on GetComponent<Text>() if the ServerInfoText object is not found. Read the actual exception message you get and make sure you are looking at the correct line/object.
Since your objects are already created in your scene, there's no advantage to using GameObject.Find to get references to the objects. It would be more efficient to directly set the references to the objects via the inspector. This option has the added benefit of working with disabled GameObjects. Either make your two member variables private, or use the SerializeField attribute to make the properties visible in the inspector.

Unity SetActive(True) Not working?

so I've been spending the past 9 hours trying to fix this. I have a weapon attached to a plane. I want this weapon to appear and be functional, after I get a specific number of kills. It does dissapear when I want it to, but it does not appear back. Also, I cannot use it while it is not visible.
Suggestions? Anyone who can see the problem here, is my saviour!
private GameManager game;
GameObject weapon_rocket;
// This works - Start class removes the object any creates any necessary referances
public void Start ()
{
weapon_rocket = GameObject.Find("weapon_rocket");
weapon_rocket.SetActive(false);
GameObject Player = GameObject.Find("Player");
game = (GameManager)GameObject.FindObjectOfType (typeof(GameManager));
GameManager gameManager = Player.GetComponent<GameManager> ();
}
// Here it doesn't recognise SetActive(True)
public void SwitchWeapon ()
{
if (game.Killed >= 1) {
weapon_rocket.SetActive (true); // this does not make the weapon reappear for some reason
CurrentWeapon = 3; // this makes the weapon usable - doesn't work when the weapon is not visible
}
null Reference Exception Already gave you a hint.
C# has a Garbage Collector as well as Java and any other programs.
Meaning, if your GameObject is Inactive and there is no Pointer/ Reference on it. It will be eligible to be garbage collected and destroyed to free some memory. It is Automatic unless you override the Finalize() function. Which I don't recommend if you don't know how CLR C# works.
To simply fix your problem. I recommend Referencing it first so the Garbage collector will ignore it.
In your Start(), you already Reference your Object so that is not going to be Garbage collected.
But I would bet that in your Editor. Your GameObject is grayed already. Meaning you have set it by InActive by default. That is why your GameObject.Find is throwing an Exception already. Make sure it is active So GameObject.Find can reference the Object First "BEFORE" Setting it to inactive. Or else. It is Garbage Collected already. Or worse, not even going to be Instantiated in the first place.
If you just want to make the object invisible, you could consider just disabling the mesh renderer instead of the entire object. And see if that allows it to be set to true and bring it back.
It's been a while since I have been in Unity, and still somewhat new to it myself. However, from what I remember there was an issue of a deprecated feature/object/method about setting the visibility of a game object. What it ended up being moved to was to the "BEHAVIOR" of a control and setting it from there.
So, that said, and that it HAS been a while, you can probably search on unity "Behavior"
But looking at this Unity link, it also states that if the parent object is not active, neither will any child under it.
So, I hope this can help further identify and resolve your issue. I will check back on this later tonight after work if not already resolved by then.
you must convert the GameObject weapon_rocket to
GameObject weapon_rocket = null;

Categories

Resources