- Home /
Adding A Script to an Instantiated Game Object - And Adding Values - 2020
So I have been at this for HOURS! I have LITERALLY tried EVERYTHING this forum and others said to do on this matter... Most of the solutions I came across want me to do something like this:
var createdObj = Instantiate(moneyStack100k, transform.position, transform.rotation);
createdObj.AddComponent<GrabMoneyStack>();
createdObj.GetComponent<GrabMoneyStack>().currentMoneyAmt = currentMoneyAmt;
Ive literally tried it all... I either get errors, or No instantiated object doing it this way? Also almost every solution I've come across is from years ago.. With warnings of being Deprecated?
The issue here, is im trying to check if the Amount of a money stack is a certain amount. If its at (for example) depleted passed 1000000, then what ever money objects thats there, will be destroyed, and replaced with the new (Smaller money Object). Now this works with regular Instantiation, HOWEVER, the script doesnt transfer and neither do any values. It just spawns the money prefab with nothing on it. Which makes sense.. But I am truly stuck on this.. My sample code is actually above, here is what works but doesnt transfer the script:
Instantiate(moneyStack100k, transform.position, transform.rotation);
How do I create a new Instantiation, and literally transfer the script with all desired values to it? Any help is seriously appreciated, thanks.
Answer by EsC369 · Aug 17, 2020 at 05:08 PM
Ok guys, Update here: So I have boiled it down to an edge case within my money script that would destroy the Gameobject if it were 0. Since I didnt get a chance to add the AMt onto it yet, it thus, would destroy the instantiation. Now, Im somewhat passed that hurddle. Now I unfortunately have to transfer like 6 different variables to the new prefab.. I for sure will have to change this layout to be more efficient, but for the time being, I am still curious how to transfer a variable GAMEOBJECT From one script to the other? Just as I have been with the variables, how would one do this with the gameobject prefabs themselves?
The new prefab, doesnt have most of the gameobjects attrached?
UPDATE: It appears I got everything to work. The main issue was not only the fact that one of my edgecases was hitting before it was supposed to, deleting the instantiated object right as its created. But more so That the prefabs themselves needed to have the script and collider embedded within the new prefab I have. Then, drag these customed prefabs into my aseets to finalize the prefab to be a new and original (seperate) prefab, then, set the gameobjects to these newly created prefabs.
What I was doing before, was calling the meshed model, with nothing attached to it, except a new script with new values or gameobjects.
Not sure if that made sense, but this is what fixed it.
Solution: Create new prefabs out of the models/prefabs of your desire, go INSIDE the prefab itself, and in here, (Not within the hierarchy) Add the scripts and colliders/rigidbodies. From here, go back to the hierarchy and now drag the prefab you just added everything to into your assets folder to finalize it into being a new prefab with said script and colliders now save to it. and load these new customs prefabs/Gameobjects into the script rather than the regular Model/Prefab.
Q: How do I create a new Instantiation, and literally transfer the script with all desired values to it?
A: Create new prefabs out of the models/prefabs of your desire, go INSIDE the prefab itself, and in here, (Not within the hierarchy) Add the scripts and colliders/rigidbodies. From here, go back to the hierarchy and now drag the prefab you just added everything to into your assets folder to finalize it into being a new prefab with said script and colliders now save to it. and load these new customs prefabs/Gameobjects into the script rather than the regular $$anonymous$$odel/Prefab.
your marked answer does not make sense, if people come here they are better off looking at another answer if they need help instantiating/modifying values of an gameobject.
Answer by xxmariofer · Aug 17, 2020 at 08:55 AM
your code is fine, there is no other way of doing this, that code cant give any warnings nore not insntaite the object, your error most likely is understanding script execution order if you are for example setting currentmoneyatm to 0 for example in the start method, you are setting the value here
createdObj.GetComponent<GrabMoneyStack>().currentMoneyAmt = currentMoneyAmt;
and overriding the value in the start event, change start to awake if thats the case
For sure, thanks for the celerity. I now know that it is some of my other code affecting this, maybe even destroying the object somewhere. Since there was no prefab, I assumed it never instantiated. But apparently its being destroyed somewhere after the instantiation. I will def look into this here soon. For the record, I don't have an update methods, and my start method only checks the money amounts and instantiates the desired prefab per amount. I am not setting any values to the money amount until AFTER the check has completed. Within my check/instantiation script, it returns a bool, and from there the grab continues if successful money check. SO no values are even hindered until after the instantiations. But thank you for the insight regardless.
Answer by TomArano_Dimenco · Aug 17, 2020 at 09:30 AM
as @xxmariofer noted.. the code you show does not seem to have any problems, this is still the way to do it. (as we speak I even have code open right now that does almost exactly the same..)
that being said, your problem has to be elsewhere in you code..
do u have some static values somewhere of singleton behaviour?
If you are willing to post more of your code i'm sure one of us will be able to spot that error somewhere.
Another option is to start again in a new scene (or even project) and just have 2 simple scripts to test this behavior and go from there, if u cant get it to work in this new scene u are gonna have to post more code as u do now.
public class spaceSpawnObject : $$anonymous$$onoBehaviour
{
public GameObject prefab;
public float valueToPassOn;
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
GameObject go = Instantiate(prefab);
go.name = valueToPassOn.ToString();
SpawnAbleObject sao = go.GetComponent<SpawnAbleObject>();
sao.valuetoset = valueToPassOn;
}
}
}
public class SpawnAbleObject : $$anonymous$$onoBehaviour
{
public float valuetoset;
}
Added example scripts, just tested this to work, u need an empty game object to attach the top script to, and an prefab (or gameobject reference) that has the other script. assign the prefab to the 'prefab' field int he inspector
Interesting. I will try something similar if I cant find any other issues that is destroying my gameobject after instantiation. Thanks you very much for this! Very good insight!
So I simplified it a bit more, but here is literally all im doing. I did have this a bit more modularization with helper functions and whatnot, but this is literally all im doing. For example I set the Amt of the money stack to be 100k. It should deleted the bigger stack of money that it currently is, and then instantiate the new (Smaller money stack ) prefab, with the script attached to it. Currently I am not even transferring or manipulating any values for purpose of pinpointing the issue.
The issue, is the code is simply NOT instantiating an object. I even watched my hierarchy, nothing is created. It just simply deletes the Old (Bigger money stack) but never instantiates the new one.
public void Start()
{
Debug.Log("hitting here in the start function:");
// Try Instantiating the initial models for money stacks from the get go
if(current$$anonymous$$oneyAmt != null)
{
Check$$anonymous$$oneyAmt(current$$anonymous$$oneyAmt);
}
}
public bool Check$$anonymous$$oneyAmt(int curr$$anonymous$$oneyAmt)
{
Debug.Log("Testing Hitting check $$anonymous$$oney Amt");
if(curr$$anonymous$$oneyAmt > 100000 && curr$$anonymous$$oneyAmt <= 250000 && !alreadyChanged250k) // CHeck if amt is within 100k to 250k:
{
// destroy current money stack:
Destroy$$anonymous$$oneyStack();
// Replace stack with 250k money stack:
Spawn$$anonymous$$oneyStack250k();
// DONT WORRY ABOUT THIS HERE, THE STAT$$anonymous$$ENT BELOW IS WHAT I$$anonymous$$ TESTING, IT SHOULD BE CHANGING THE PREFAB TO THE 100K $$anonymous$$O$$anonymous$$ AS IT STARTS WITH THE 250K $$anonymous$$O$$anonymous$$.
}else if(curr$$anonymous$$oneyAmt > 50000 && curr$$anonymous$$oneyAmt <= 100000 && !alreadyChanged100k) // CHeck if amt is within 50 to 100k:
{
Debug.Log("hitting here 100k SPawn money functuion:");
// destroy current money stack:
Destroy(this.gameObject);
var createdObj = Instantiate(moneyStack100k, transform.position, transform.rotation);
createdObj.AddComponent<Grab$$anonymous$$oneyStack>();
alreadyChanged100k = true;
return true;
}else if(curr$$anonymous$$oneyAmt > 30000 && curr$$anonymous$$oneyAmt <= 50000 && !alreadyChanged50k) // check if within 30k to 50k ETC......
NOte: If I remove the Destroy, then the Old 250k $$anonymous$$Odel stays, obviously) but Just wanted to express I am NOT deleted the newly instantiated object, it simply is NEVER being instantiated?
WEIRD!! SO check it out, I noticed that it was getting hung right at the instantiation. I remove the line below where its adding the money script (supposedly). When commenting that out, EVERYTHING WORKED! Well, in terms of instantiating the desired prefab finally. HOWEVER, I now realize whats happening, is I have an edge case that checks if its A$$anonymous$$T is 0. since the new prefab is created (currently as I removed any implementations of the values for testing) It thus NEVER had a value, THUS, would hit my edge case and THUS finally, destroying my instantiation... SO It was in fact my code destroying the new instantiation. Whats crazy is it was so fast, Id idnt even see a fluctuation within my hierarchy. Although I havent fixed the issue yet, I feel I am now on the right track, thank you so much! I will post here the fixes.
Your answer
Follow this Question
Related Questions
Change script from EditorWindow 0 Answers
Prefab component not linking to destination 1 Answer
How to run script in editor 1 Answer
Mech building game Parsing a large number of Prefabs 0 Answers
How to ad a money withdraw option in android game? 4 Answers