- Home /
insert script question
is it possible to insert a script into a gameobject from another gameobject after a var of maxDistance of 2 is reached? im pretty sure it has to do with the .GetComponent but an answer would be appreciated
Answer by save · Mar 20, 2013 at 12:13 AM
Yes it's possible. To add components to GameObjects you use the AddComponent function. To check distance you can use Distance.
Check the distance and adding the component altogether:
if (Vector3.Distance(transform.position, target.position) >= 2.0)
target.AddComponent(MyScript);
You can also use sqrMagnitude instead of Distance which is a bit quicker but less precise,
JS
var squaredLength : float = Vector3(target.position - transform.position).sqrMagnitude;
CSharp
float squaredLength = Vector3(target.position - transform.position).sqrMagnitude;
When that is executed you most likely want to add a trigger which says that the object has the component. Here you could use GetComponent, but using something that gets cached is better. So for instance, you can cache the script and tell things to it once it's attached. Extending the previous example a bit:
JS
private var targetScript : MyScript;
function Update () {
if (targetScript==null) {
if (Vector3.Distance(transform.position, target.position) >= 2.0) {
// Attach the target script as it wasn't yet attached
targetScript = target.AddComponent(MyScript);
}
} else {
// The target script is attached and ready for action
targetScript.someVariable = variableFromThisScript;
}
}
CSharp
using UnityEngine;
using System.Collections;
private MyScript targetScript;
void Update () {
if (targetScript==null) {
if (Vector3.Distance(transform.position, target.position) >= 2.0) {
// Attach the target script as it wasn't yet attached
targetScript = target.AddComponent(MyScript);
}
} else {
// The target script is attached and ready for action
targetScript.someVariable = variableFromThisScript;
}
}
Your answer
Follow this Question
Related Questions
How to get a variable value from another script(C#)? 1 Answer
C# GetComponent Issue 2 Answers
Accessing a value in a script attached to another game object 3 Answers
C# Rotate GameObjects Regardless of List Size 2 Answers
Creating a single-line function for GameObject.Find and GetComponent (for multiple components) 3 Answers