Is it possible to modify details of a script while the game is running?
I need a projector shadow to instantiate and follow prefabs as and when they are instantiated.
The first prefab that is created is given the gameobject name “cube0”, when this is instantiated a projector shadow is also created and told to follow cube0 with the following code:
As I continue to instantiate new prefabs (cube1, cube 2 etc) I need to instantiate more instances of the same shadow projector but make sure they each point towards the correct game object (ie follow cube1, cube 2 etc)
but I’m not quite sure how to automate this in code, I thought about making the “object to follow” a variable and changing this every time a new prefab is instantiated, but I don’t think this is going to work as all the existing shadows already in the scene will start to follow the wrong object.
I get the feeling the solution to this is simple, but my brain is failing me this morning
Try to child it instead at instantiation. Never use the find-function more than once for an object that should remain the same (doing it inside Update literally eats juice).
var theBlob : GameObject;
var cubePrefab : GameObject;
private var cube : GameObject;
private var cubeNumber : int = 0;
function Start () {
cube = GameObject.Find("cube"+cubeNumber.ToString());
}
function Spawn () {
cube = GameObject.Find("cube"+cubeNumber.ToString());
//or
cube = Instantiate(cubePrefab, thePosition, theRotation);
cube.name = "cube"+cubeNumber.ToString();
thisBlob = Instantiate(theBlob, cube.transform.position, Quaternion.identity);
thisBlob.transform.parent = cube.transform;
cubeNumber++;
}
This way you won't have lots of `transform.position` setting and could have lots of cubes with blob shadows.
Every cube (or instantiated prefab) needs it’s own projector shadow yes - originally I actually included the shadows as a child of each prefab and then attempted to use a script on the shadow which forced it look downwards in world space despite what the parent prefab was doing (the prefabs are flung through the air with rotation) but I could never get this to work reliably, behaviour seemed buggy and as the parent rotated the projector would often become misaligned or offset from the parents centre of origin slightly. If I could find a way of making this method work I would prefer it over other solutions as I like the simplicity of shadows being grouped with objects without the need for scripting.
Your idea of matching shadow arrays with an object array seems appealing as I already have a list of instantiated prefabs stored in an array (if you can imagine the player is given access to each prefab one after another almost like the way blocks are received in a queue when playing Tetris) so I guess I could look into that.