I made this extension method in order to have more feedback on instances i retrieve but i can’t find a way to call it in my gameobject script. I am doing something wrong ? I added the correct namespace so i can access it but there no way i can use the method directly in the awake method of my game object.
Any ideas why ?
/// <summary>
/// Improved safe version of the FindObjectOfType which can find a GameObject in the scene.
/// </summary>
/// <typeparam name="T">Type of the GameObject to search for.</typeparam>
/// <param name="obj">GameObject.</param>
/// <returns>GameObject found.</returns>
public static T FindSafeObjectOfType<T>(this UnityEngine.Object obj) where T : UnityEngine.Object
{
T found = (T) UnityEngine.Object.FindObjectOfType(typeof(T));
if (found == null)
{
Debug.LogError(string.Format("Expected to find GameObject of type ({0}) but found none.",
typeof(T)), obj);
}
return found;
}
I can’t think of a way you could get that to compile, without it also working as you say it’s not. It works for me.
What is the point of this function, though? FindObjectOfType is in the API.
Also, tip: this belongs in the UnityEngine namespace. If it weren’t already there, you should have put it in there instead of using a using statement, or typing out UnityEngine.
C# doesn’t have the concept of an object that can’t be null. There’s no point in singling out FindObjectOfType; every function that returns an object or nullable struct has the potential to return null. It’s bad design, but not Unity’s fault. That said, I do think the return value of FindObjectOfType makes sense to be a nullable.
public static T WithLoggedErrorIfNull<T>(this T t) {
if (t == null) Debug.LogError(
string.Format("Expected object of type {0} but got null.", typeof(T)) );
return t;
}
var meshCollider = FindObjectOfType<MeshCollider>().WithLoggedErrorIfNull();
Alright, you probably right there. There not much value in encapsulating everything related to logged with theses methods. So i think i will go the suggested route with WithLoggedErrorIfNull. Seem cleaner!