I want to make my own tile system and right now I’m working on root object that will act like a controller for tiles, storing general information about tile size etc.
What I want to do is to place this tile root in (0, 0, 0), set it’s scale and rotation to (1, 1, 1) and restrict changing it’s transform values.
I’ve tried to use MonoBehavior’s OnValidate(), but it does not work properly. I still can drag root and change it’s transform’s values in editor and it does not resets. Any ideas?
Here is the code, btw.
using UnityEngine;
using System.Collections;
public class TS_Root : MonoBehaviour {
private static TS_Root instance;
public static TS_Root Instance
{
get
{
if(instance == null)
{
GameObject temp = new GameObject();
temp.name = "TS_Root";
instance = temp.AddComponent<TS_Root>();
}
return instance;
}
}
public static int TileWidth = 64;
public static int TileHeight = 64;
[ExecuteInEditMode]
void OnValidate()
{
if(instance == null) instance = this;
if(transform.position != Vector3.zero) transform.position = Vector3.zero;
if(transform.localScale != Vector3.one) transform.position = Vector3.one;
if(transform.rotation != Quaternion.identity) transform.rotation = Quaternion.identity;
}
}
You can use HideFlags for this. Each component on a GameObject has its own hideflag value.
You can use HideFlags.NotEditable to set the component as not editable in the inspctor.
If you want to hide the component as well then you can use HideFlags.HideInInspector.
So for restricting movement you can set the Transform to not be editable:
The Transform will be grayed out and non of its values will be editable, but the handles for the object in the scene will still work, so if you want to restrict that then you need to set the gameOBject to not editable as well:
targetObject.hideFlags = HideFlags.NotEditable;
This makes layers, tags and Name also not editable though.
This also has the unfortunate effect of setting the HideFlags of all attached components to NotEditable as well, so if you want the GameObject to not be editable but specific components on the GameOBject be editable, you will need to specifically enable them afterwards: