I have an object that is enabled/disabled continuously because it’s being used in object-pooling. An outside “pooling” class enables/disables it via SetActive() and the object has parameters in OnEnable() that set it’s position when it’s enabled. I want to pass a coordinate to its OnEnable(). In this example, can an outside class pass the value for z?
using UnityEngine;
using System.Collections;
public class Foo : MonoBehaviour {
public Vector3 StartingPoint;
void OnEnable (float z) {
StartingPoint = new Vector3(0.0f, 1.0f, z);
}
}
No. None of the ‘Unity constructors’ get to have parameters.
One way around this is to use a factory type pattern. You can have another class, or a static member on this class, that takes care of enabling and setting up the defaults. You can also throw an error if the class is ever enabled through means other then the proper factory.
Thanks for the reply BoredMormon. I’m very tired and totally botched my question. The parameters I want to pass are to OnDisable(). Is that still a no-go?
using UnityEngine;
using System.Collections;
public class Ground : MonoBehaviour {
public Vector3 StartingPoint;
public float speed;
void OnDisable(float z) {
transform.position = new Vector3(0, 0, z);
}
}
Unity will attempt to call a method with the signature OnDisable(), it will never call OnDisable(float z)…
What are you trying to achieve? Remember, the methods OnDisable(), Awake(), Start(), OnDestroy(), etc are invoked by Unity as per their lifecycle rules. You should never call any of these methods directly (while it will work, it’s not how they’re supposed to work).
Let’s be wild and imagine that Unity did call your OnDisable(float z) method, what value would Unity pass for ‘z’? It knows nothing about your float z.
if you have a reference to the ground script, then you also have a reference to its transform. so just have the script that disables it also set it’s position. if its some other property you can simply access it through a public variable/property/function
if you’re worried about decoupling then write a mediator class, or an interface that will handle it
How about this? (Still seems weird code to me though, this Z change is very situational i guess.)
public class Ground : MonoBehaviour {
public Vector3 StartingPoint;
public float speed;
public float disabledZ;
void OnDisable() {
transform.position = new Vector3(0, 0, disabledZ);
}
}