- Home /
Getting values from inspector into scripts
Super beginner question how do I get this value into my script? (c#)

Answer by tw1st3d · Jul 27, 2013 at 06:05 PM
Click on the script that is on your object,(Targeting.cs) and you'll see the variable being created inside of that. Next, create a new script, let's say TargetingModifier.cs
using UnityEngine;
using System.Collections;
using System;
class TargetingModifier : MonoBehavior
{
// I don't have Targeting.cs, so it's either
// An asset, or your own code, so we'll say
// its class name is Target
public Target theTarget = new Target();
// Create a new variable instantiating
// A new instance of class "Target"
// Next, call a variable from it.
public Transform getTarget = theTarget.SelectedTarget;
// Now, let's do something with it.
void Update()
{
if(!getTarget == null)
{
// If the target is actually set,
getTarget.Destroy();
// Destroy it
}else{
// If it's NOT set,
getTarget = GameObject.Find("TheTarget");
// Set it as a target
}
}
}
Answer by Owen-Reynolds · Jul 27, 2013 at 06:24 PM
If you already have that script made, drag anything from the "scene objects" panel (named Hierachy) into that slot. You have to select the thing with the script (like your picture) and then drag the other thing (without clicking on it.) If it works, it will highlight and "None(Transform)" will be replacead. You double-check by clicking that slot. The real item should turn yellow.
In the script the variable SelectedTarget will magically be aimed at that thing you dragged.
It is legal to drag a prefab into the slot (from Project,) but don't. Your target would be something not in the game yet, so wouldn't make sense (it will just do weird stuff.)
Of course, that only works it the object will always have that one thing for a target. If it can switch, the script has to do the work. Then there's no point dragging.
I don't think he's asking how to set an object into the variable, but how to access the variable itself through code.
Yeah the over all goal is to lock on to a target and then fire missiles at the target.
Just didn't know how to pass the value from the targeting script to the missile guidance script.
The giant picture of the Inspector, and "Getting from Inspector" in the title, threw me off.
While the program runs, the Inspector is just a view of some variables, and doesn't do anything. So, in code, you never have to do anything special to set or read an Inspector variable. Just write a regular program and set/read everything the usual way.
Your answer