Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

464
Views
Inspector personalizado que revierte los valores a valores anteriores en Play in Unity

Entonces, en mi juego, tengo un objeto que necesito mover sin problemas desde Vector3 fromPosition a Vector3 toPosition a speed float speed , y luego volver a donde comenzó. Todo muy simple, pero para tratar de hacer la vida más fácil al configurar niveles, decidí crear un inspector personalizado para este script con botones que me permiten establecer las posiciones de destino en la posición actual del objeto, de modo que pueda moverlo a donde debe estar y haga clic en un botón, en lugar de escribir todas las coordenadas. Pensé que tenía todo funcionando, pero luego comencé a ver un comportamiento muy extraño, después de jugar, parece ser el siguiente: La primera vez que se usa un botón, todo está bien. Cada vez que se usa el botón después de eso, los valores cambian correctamente en el inspector, pero al presionar Reproducir, los valores de toPosition y fromPosition se revierten a los que tenían la primera vez que se usó el botón. (No vuelven atrás en Stop). Sin embargo, si escribo los valores manualmente, funciona perfectamente. Muy extraño, ¿alguien tiene idea de lo que podría estar pasando aquí? El código para el script y el inspector personalizado se encuentran a continuación.

 using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; public class MovingGrapple : MonoBehaviour { public Vector3 fromPosition; public Vector3 toPosition; public float speed; Rigidbody thisBody; Grapple player; // Start is called before the first frame update void Start() { thisBody = GetComponent<Rigidbody>(); player = GameObject.Find("Head").GetComponent<Grapple>(); } private void FixedUpdate() { thisBody.MovePosition(Vector3.MoveTowards(transform.position, toPosition, Time.fixedDeltaTime * speed)); if(transform.position == toPosition) { transform.position = fromPosition; if (player.activeTarget != null && GetComponentsInChildren<Transform>().Contains(player.activeTarget.transform)) { player.BreakGrapple(); GameObject.Destroy(player.activeTarget); } } } public void SetFromPosition() { fromPosition = transform.position; } public void SetToPosition() { toPosition = transform.position; } }
 using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; [CustomEditor(typeof(MovingGrapple))] public class MovingGrappleInspector : Editor { public override void OnInspectorGUI() { DrawDefaultInspector(); MovingGrapple myTarget = (MovingGrapple)target; if (GUILayout.Button("Set From position.")) { myTarget.SetFromPosition(); } if (GUILayout.Button("Set To position.")) { myTarget.SetToPosition(); } } }

Gracias.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Esto no solo sucederá si presiona reproducir ... ¡sus cambios nunca se guardan!

Si es posible, nunca debe mezclar secuencias de comandos del editor con acceso directo al target , ¡a menos que sepa exactamente lo que está haciendo!

Especialmente necesitaría marcar "manualmente" su objeto cambiado como sucio . De lo contrario, los cambios son solo temporales hasta que su objeto se deserialice nuevamente (Entrar/Salir del modo de reproducción o recargar la escena o el activo).

Antes de los cambios, podría agregar unUndo.RecordObject

 if (GUILayout.Button("Set From position.")) { Undo.RecordObject(myTarget, "SetFromPosition"); myTarget.SetFromPosition(); } if (GUILayout.Button("Set To position.")) { Undo.RecordObject(myTarget, "SetToPosition"); myTarget.SetToPosition(); }

Además (suena poco probable en su caso de uso, pero)

Importante: para manejar correctamente las instancias en las que objectToUndo es una instancia de Prefab, se debe llamar a PrefabUtility.RecordPrefabInstancePropertyModifications después de RecordObject .


En general, siempre vaya a través de SerializedProperty cuando sea posible, como por ejemplo

 [CustomEditor(typeof(MovingGrapple))] public class MovingGrappleInspector : Editor { private SerializedProperty fromPosition; private SerializedProperty toPosition; private MovingGrapple myTarget private void OnEnable() { fromPosition = serializedObject.FindProperty("fromPosition"); toPosition = serializedObject.FindProperty("toPosition"); myTarget = (MovingGrapple)target; } public override void OnInspectorGUI() { DrawDefaultInspector(); // This loads the current real values into the serialized properties serializedObject.Update(); if (GUILayout.Button("Set From position.")) { // Now go through the SerializedProperty fromPosition.vector3Value = myTarget.transform.position; } if (GUILayout.Button("Set To position.")) { toPosition.vector3Value = myTarget.transform.position; } // This writes back any changes properties into the actual component // This also automatically handles all marking the scene and assets dirty -> saving // And also handles proper Undo/Redo serializedObject.ApplyModifiedProperties(); } }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!