Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Help: Custom Grid Builder

Discussion in 'Scripting' started by Harbinger-Czar, Jun 25, 2018.

  1. Harbinger-Czar

    Harbinger-Czar

    Joined:
    Jun 25, 2018
    Posts:
    7
    I'm trying to create a custom grid building tool. Every time I try to run it, it creates one cube then stops. Any thoughts?

    Script:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class GridBuilder : MonoBehaviour {
    6.  
    7.     public float x;
    8.     public float z;
    9.  
    10. }
    Editor Script:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEditor;
    5.  
    6. [CustomEditor(typeof(GridBuilder))]
    7. public class GridBuilderEditor : Editor
    8. {
    9.     public float x;
    10.     public float z;
    11.  
    12.     public override void OnInspectorGUI()
    13.     {
    14.         base.OnInspectorGUI();
    15.  
    16.         if (GUILayout.Button("Create"))
    17.         {
    18.             for (int i = 0; i <= z; i++)
    19.             {
    20.                 for (int j = 0; j <= x; j++)
    21.                 {
    22.                    
    23.                     GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
    24.                     cube.transform.position = new Vector3(j, -1, i);
    25.                 }
    26.             }
    27.         }
    28.     }
    29. }
     
  2. Madgvox

    Madgvox

    Joined:
    Apr 13, 2014
    Posts:
    1,315
    You're using the local x and z values of the GridBuilderEditor, which are always 0. You need to use the x and z values of the GridBuilder, which you can access via
    ((GridBuilder)target).x
    or
    .z
    .
     
    Harbinger-Czar and xVergilx like this.
  3. Harbinger-Czar

    Harbinger-Czar

    Joined:
    Jun 25, 2018
    Posts:
    7
    It's giving me an error on target for "A field initializer cannot reference the non-static field, method, or property 'Editor.target'."
     
  4. Madgvox

    Madgvox

    Joined:
    Apr 13, 2014
    Posts:
    1,315
    I didn't say to set the GridBuilderEditor x and z to the GridBuilder x and z. :D

    I said that you don't need GridBuilderEditor to have x and z fields. Use GridBuilder's x and z in your loops.