- Home /
How do I make it so every object the player creates (in a building game) gets a script attach to it by default?
For context, I'm trying to make a building game. I already have a script attached to an empty that allows the player to press P to spawn an object then left click to place. Now I'm following a tutorial to make it so the player can click on a game object and move it around. However, I believe the script requires an object to be attach to that will be moved around. This is why I'm looking for a way to automatically apply that script to every object that the player creates. Not only that, but it would also be useful for other things like allowing the player to rotate their object when they select it.
So how would I do that? Or is there another method that can achieve the same results? Thank you in advance.
Answer by Caeser_21 · Feb 21 at 12:22 PM
First, make every object that the player spawns have the same tag (For example "BuildObject")
Then, add this to beginning of the script
private GameObject[] BuildObjs; //This is where you store the Gameobjects that the player created
[SerializeField] private someScript SS; //This is the script you want to be added to BuildObjs
After that add this in the script
void Update()
{
BuildObjs = GameObject.FindGameObjectsWithTag("BuildObject");
foreach (GameObject Object in BuildObjs)
{
if (Object.GetComponent<someScript>() == null)
{
Obj.AddComponent<SS>();
}
}
}
This should work... i think
IMPORTANT NOTE : Instead of "someScript" you have to put the name of the script you want to add.
Answer by Monsoonexe · Feb 21 at 12:38 AM
Consider someGameObject.AddComponent<SomeCustomComponent>();
https://docs.unity3d.com/ScriptReference/GameObject.AddComponent.html
Answer by David0199 · Feb 22 at 10:47 AM
Looking for the same issue. Bumped into your thread. Thanks for creating it. Looking forward for solution.
@$$anonymous$$0199 You can use the solution I have given at the top of the thread, it should work
Your answer
![](https://koobas.hobune.stream/wayback/20220613053257im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
PreFabs, How do they work? Why the object not longer responds to what the script says? 1 Answer
Distribute terrain in zones 3 Answers
How to render a particle system with a preset particle system in a prefab? 0 Answers
instantiating unique classes of a type 0 Answers