- Home /
"Instantiate"/make new function via script?
Hi,
is it possible to somehow make a new function within the same script? It can be the same function with different parameters, so maybe there's a way like instantiating it like a object from a class?
Background: I came up with the idea of making a simple occlusion culling for Unity free. Currently I make an empty gameobject and attach my following script for each object-(group) I want to cull:
var toCul : GameObject; //(group of) object(s) we want to be active only when we are in...
var culRange : int = 100; //...this range
function Awake() {
toCul.SetActive(false); //deactivate the "problem"-object(s) at start
}
CheckRange(0);
function CheckRange(waitFor : int) : IEnumerator {
yield WaitForSeconds(waitFor);
var curRange : int = Vector3.Distance(Camera.main.transform.position, toCul.transform.position); //range from the camera to the object
if (curRange < culRange) {
toCul.SetActive(true); //if in reach activate the object...
} else {
toCul.SetActive(false); //if not, deactivate it
}
var checkIn = Mathf.Max(0.5, 5*curRange/culRange); //the next check depends on the range from the camera to the object (for better performance)
CheckRange(checkIn);
}
It works great and currently I just have 3 of them on my empty gameobject. But I wonder how I could extend this to work on just one single script so I could store all my objects i want to cull in an array and for each index there's automaticly made a "CheckRange"-function like in the code?
Answer by Loius · Mar 20, 2013 at 07:45 PM
Just re-write InvokeRepeating in your manager.
var objs: Cullable[] = whatever;
InvokeRepeating(CheckRanges...);]
function CheckRanges() {
for ( var i in objs ) {
i.CheckRange();
}
}
Thx, but maybe I was not so clear: I have this script above not attched on the objects that I want to cull, I have the scripts all on one single gameobject. In the inspector I can now drag may objects which I want to cull on the "toCul" variable.
If I interprete your script right, you would access the function in my script, if the objects I want to cull had my script attched. But this is not the case and can't work because I want to activate/deactivate these objects complete, so I can't attach some sort of check-range script or similar.
var objs: Cullable[] = whatever;
InvokeRepeating(CheckRanges...);]
function CheckRanges() {
for ( var i in objs ) {
// insert your CheckRange function here but replace 'this' with 'i', so 'transform.position' becomes 'i.transform.position'
}
}
Ok, now I understand, but I should make also a new list for the ranges. It's more like a workaround for my problem, but for others this would probably help, so I mark as correct answer :)
Your answer
Follow this Question
Related Questions
Instantiate A Prefab 1 Answer
function Start () problem!! 3 Answers
The Walking Dead Game Animation Style 1 Answer
Calling a Function from other script ( C# ) 1 Answer
Questions of the Coroutines 1 Answer