0
\$\begingroup\$

In the mono script :

using UnityEngine;

public class TileTest : MonoBehaviour
{
    public GameObject prefabPathOnTerrain;

Then in the editor script at the top :

private SerializedProperty prefabPathOnTerrain;

Then inside OnEnable()

private void OnEnable()
    {
        prefabPathOnTerrain = serializedObject.FindProperty("prefabPathOnTerrain");
    }

And then inside a method I want to use it as a GameObject : And instead using CreatePrimitive to use Instantiate : But doing :

GameObject go = Instantiate(prefabPathOnTerrain);

Will not work.

public void TerrainObjects(GameObject gameobject)
    {
        Terrain terrain = Terrain.activeTerrain;
        var cube = GameObject.Find(string.Format("Terrain_{0}_{1}", gameobject.transform.localPosition.x, gameobject.transform.localPosition.y));
        if (cube != null)
            return;

        if (cube == null)
        {
              GameObject go = Instantiate(prefabPathOnTerrain);              

            //cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
        }

        cube.transform.localPosition = new Vector3(terrain.transform.localPosition.x + gameobject.transform.localPosition.x, 0, terrain.transform.localPosition.z + gameobject.transform.localPosition.y);
        cube.transform.localScale = new Vector3(gameobject.transform.localScale.x, gameobject.transform.localScale.y, 1);
        cube.transform.parent = GameObject.Find("Terrain Map").transform;

        cube.name = string.Format("Terrain_{0}_{1}", gameobject.transform.localPosition.x, gameobject.transform.localPosition.y);
        cube.tag = "Terrain Map";
    }
\$\endgroup\$
1
\$\begingroup\$

Don't forget to read the documentation for the data types you're using.

A SerializedProperty could potentially hold any kind of data the Unity serializer supports. It's like backpack with different zippered pockets for different things you might want to carry. So if you want a particular kind of data out of it, you need to unzip the right pocket.

For a reference to a game object, that's the .objectReferenceValue pocket. So you want something like this:

var prefab = (GameObject)prefabPathOnTerrain.objectReferenceValue;

We have to cast it to the type we expect, because an objectReferenceValue could reference any Object type.

Then you can check whether the prefab is non-null and instantiate as normal.

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ I might make a new question because I've never heard of SerializedProperty before. What is that for? \$\endgroup\$ – jhocking Aug 2 at 12:21
  • 2
    \$\begingroup\$ @jhocking it's used for navigating and manipulating the exposed parameters on a script in a custom inspector or editor. \$\endgroup\$ – DMGregory Aug 2 at 14:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.