Assign Value to prefab on instantiation

Hello All,

New guy here, so bear with me! I want to instantiate gameobjects from a prefab at run time so that when the object is raycasthit it returns the animation sequence to play on the player.

I can instantiate the objects, but I am trying to set the name of the animation on/in the script attached to the instance. The when the object is triggered I can retrieve the animation name and play it on the target.

Can anyone point a novice in the right direction? What would be the sensible way to implement this? i.e. prefab, instantiate instance, assign unique value to it, user input/collision indicates it hit, get that instances' value, play that animation on target.

A general response is cool, too... don't give me too many spoilers!!

Thanks!

To sum it up, you want to store a value with an instantiated prefab and then retrieve the value elsewhere (raycast), right? You would do it exactly as described:

  1. Create a script attached to the prefab which has a public variable for storing the value.
  2. In the script where you instantiate the object, set the value of the variable in the script attached to the prefab instance.
  3. Retrieve the value from the script attached to the instance elsewhere.

Something like this:

PrefabInfo.js (attached to prefab)

var animationName : String = "";

InstantiateSetString.js

var prefab : Transform;

//somewhere
var instance = Instantiate(prefab, somePosition, someRotation);
var script : PrefabInfo = instance.GetComponent(PrefabInfo);
if(script) script.animationName = "foo";
//You can eliminate this check if you know the prefab has this script and
//you could even write it in one line like so:
//
//Instantiate(prefab,somePosition, 
//    someRotation).GetComponent(PrefabInfo).animationName = "foo";

RaycastCheckString.js

//somewhere
var animationName : String = "";
var hit : raycastHit;
if(Physics.Raycast(transform.position, transform.forward, hit) {
    var script : PrefabInfo = hit.gameObject.GetComponent(PrefabInfo);
    if(script) animationName = script.animationName;
    //Or you could just drop the local animationName variable completely
    //
    //if(script) animation.Play(script.animationName);
    //
    //Again, depending on your setup, if you know the script is there,
    //you could drop the variables and if statement.
}