- Home /
How to add components to other GameObjects through a C# script attached to one?
For example, I want to attach a script named "AddMultiComponents" to an GameObject(button) named "StartButton". On click, StartButton will add the component RigidBody2D to another GameObject named "FallingSphere".
If possible, please provide an in-depth explanation. Thank you very much.,If possible, please give an in-depth explanation as I'm a total amateur in Unity scripting. Thank you very much.
Answer by robert97mc · Jul 08, 2019 at 04:16 PM
Create script called "AddMultiComponents" to a GameObject named "StartButton" 2.Add code to a script:
using UnityEngine;
public class AddMultiComponents : MonoBehaviour { //Here attach "FallingSphere" object in inspector public GameObject fallingSphere;
//This function will add component Rigidbody2D on click public void AddRigidbodyComponent() { fallingSphere.AddComponent<Rigidbody2D>(); } }
3.Just add this function on "StartButton" on click list.
Answer by promant12 · Jul 08, 2019 at 04:37 PM
Adding a component to an existing object is not the right way to go. It uses relatively large portion of memory and it's unnecessarily complicating the code. Instead, add a RigidBody to the 'FallingSphere' in the inspector and just disable it by hitting that small box right next to the component's name. Then enable it via code when you need to, simply by putting
public void YourVoidName()
{
GetComponent<RigidBody>().enabled = true;
}
to a script attached to your Falling Sphere.Last thing you need to do is placing this script in the button's "On Click ()' field in the inspector and pick your YourVoidName.
Your answer
Follow this Question
Related Questions
Cannot destroy Component while GameObject is being activated or deactivated 2 Answers
"There is no 'GameObject' attached to the "x" game object' 2 Answers
Is there a way to dynamically attach a script to a GameObject during runtime? 1 Answer
Can't disable component, little checkbox is missing from inspector 1 Answer