- Home /
How to change position of multiple objects using Editor Script in C#?
I want to change multiple objects position while in editor mode, i can do that by dragging them in scene view but how do I change say, their x position from the inspector?
here's a screenshot of the objects and there transform:
as you can see the position x is dashed out. I wanted to do it using editor script. This is the script in Editor folder.
using UnityEditor;
using UnityEngine;
using System.Collections;
[CustomEditor(typeof(ChangePuzzlePosScript)), CanEditMultipleObjects]
public class ChangePuzzlePosEditor : Editor {
public override void OnInspectorGUI()
{
DrawDefaultInspector();
ChangePuzzlePosScript script = (ChangePuzzlePosScript)target;
if(GUILayout.Button("Change Position"))
{
script.ChangePosition();
}
}
}
and this is the script The above Editor script is calling and is attached to each of the objects that I want to move. Where I have a posX float that I am adding to the objects position.x
using UnityEngine;
using System.Collections;
public class ChangePuzzlePosScript : MonoBehaviour {
public float posX = 9.6f;
public void ChangePosition()
{
transform.position = new Vector3(transform.position.x + posX, transform.position.y, transform.position.y);
}
}
This is the inspector view of the above script attached to the objects i want to move. I have the value I want to add to objects position.x and when I click the change position buttton It only changes the position for one object not all the selected ones.
What am I missing?
Thanks!
Answer by jdean300 · Jun 08, 2017 at 05:40 AM
This should work here - the key idea is that custom editors have a targets
array when you are editing multiple objects. I'm not sure if that array will be empty or have a single element if you only have one selected. If it is empty then you will need to check the length of the targets
array and use target
if it is empty.
public override void OnInspectorGUI()
{
DrawDefaultInspector();
if(GUILayout.Button("Change Position"))
{
foreach (var script in targets.Cast<ChangePuzzlePosScript >())
{
script.ChangePosition();
}
}
}
Add 'using System.Linq;' to the top of your code
change the foreach above to
foreach (var script in targets){
if (script.GetComponent<ChangePuzzlePosScript>() != null) {
script.ChangePosition();
}
}
Your answer
Follow this Question
Related Questions
Check if two objects have the same position. 2 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers