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
1 Answer
1Yes 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;
}
}