Hi, I’m new to this forum and to Unity.
Version: Unity 2017.2.1f1
My questions are in the title and in the code below.
using UnityEngine;
using System.Collections;
public class NewBehaviourScript : MonoBehaviour
{
private Vector3[] _vertices;
void Awake()
{
Generate();
// I want to call Generate() at the beginning of both edit mode and play mode.
// But this function is not called at the beginning of edit mode, what should I do?
}
void Generate()
{
_vertices = new Vector3[2];
_vertices[0] = new Vector3(-1f, 0f, 0f);
_vertices[1] = new Vector3(1f, 0f, 0f);
}
void OnDrawGizmos()
{
Debug.Log(_vertices.Length); // In edit mode, this logs the number 0,
// it means that the function Generate() is not called.
if (_vertices == null)
return;
Gizmos.color = Color.yellow;
for (int i = 0; i < _vertices.Length; i++)
{
Gizmos.DrawSphere(_vertices[i], 0.1f);
}
}
}
playModeStateChanges is not appropriate here for two reasons;
it’s editor only, meaning that if these vertices are necessary for the game instead of just gizmos, it’s not going to work.
the implementation would be a super-cumbersome “search through all objects, find the relevant objects, call the method on all of them” implementation.
The easiest thing for sure would be to use the [ExecuteInEditMode] attribute. That might not be appropriate - if you have Update methods that moves the object around, it will now be moved around in edit mode, which you don’t want. Probably.
A more robust thing would be to make the vertices be lazy:
public class NewBehaviourScript : MonoBehaviour
{
private Vector3[] _vertices;
private Vector3[] vertices { get {
if(_vertices == null)
_vertices = Generate();
return _vertices;
}
Vector3[] Generate()
{
var verts = new Vector3[2];
verts[0] = new Vector3(-1f, 0f, 0f);
verts[1] = new Vector3(1f, 0f, 0f);
}
void OnDrawGizmos()
{
Gizmos.color = Color.yellow;
for (int i = 0; i < vertices.Length; i++)
{
Gizmos.DrawSphere(vertices[i], 0.1f);
}
}
}
The code I showed you at the top is based on a tutorial, and the function Awake() is used in the tutorial, but I don’t know what did the Author do to show the Gizmos in edit mode, maybe the new Unity has a bug? The calling of the function Generate() is inside Awake() as below:
private void Awake()
{
Generate();
}
Question: So how to use the function Awake() and make it to be called at the beginning of the edit mode?
If you are curious about the tutorial then here is the link Procedural Grid, a Unity C# Tutorial
The tutorial’s image below is in edit mode because of the XYZ.