I’ve managed to save transform values (translates,rotations,scales) of my gameobject (on each frame) into a List. Now, I’m unable to assign these same values to my gameobjects transform. When I do so, I get this error -
cs(34,28): error CS0200: Property or indexer `UnityEngine.GameObject.transform’ cannot be assigned to (it is read only)
Here is the saving to the list script I’m using -
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class saveList : MonoBehaviour {
private List<Transform> Movements = new List<Transform>();
private int MovementIndex = 0;
private bool reassigning;
void Update (){
if(!reassigning)
{
Movements.Add(transform);
MovementIndex++;
}
if(MovementIndex > Movements.Count - 1)
{
MovementIndex = Movements.Count;
}
if(Input.GetKey("e"))
{
reassigning = true;
Rewind();
}else
{
reassigning = false;
}
}
void Reassign (){
MovementIndex--;
transform = Movements[MovementIndex];
//Movements.RemoveAt(MovementIndex);
}
}
Unfortunately, you so simply can’t save your Transform for different statuses. You remember the reference to object. It always same. Therefore your status not to change. And the second, it is necessary to change each Transform element manually (position, rptatio, scale). Typically, you’ll either want to do a ‘shallow copy’ or a ‘deep copy’ when copying fields from one instance of a class to another instance of the same class type. I will write a simple code with comments:
//Create class for our Transform with correct variable
public class myTrans {
public Vector3 myPos = Vector3.zero; //current position
public Quaternion myQuat = Quaternion.identity; //current rotation
public Vector3 myScale = new Vector3(1, 1, 1); //current scale
}
private List<myTrans> Movements = new List<myTrans>(); //create list of our class
private int MovementIndex = 0;
private bool reassigning;
void Update (){
if(!reassigning) {
myTrans tp = new myTrans(); //create temp variable our class
tp.myPos = this.transform.position; //save current position
tp.myQuat = this.transform.rotation; //save current rotation
tp.myScale = this.transform.localScale; //save current scale
Movements.Add(tp); //add current data in our list
MovementIndex++;
}
if(MovementIndex > Movements.Count - 1) {
MovementIndex = Movements.Count;
}
if(Input.GetKey("e")) {
reassigning = true;
Reassign(); //maybe change function Rewind() to Reassign()
} else
reassigning = false;
}
}
void Reassign (){
MovementIndex--;
//check index and count list
if (MovementIndex >= 0 && Movements.Count > 0) {
this.transform.position = Movements[MovementIndex].myPos;
this.transform.rotation = Movements[MovementIndex].myQuat;
this.transform.localScale = Movements[MovementIndex].myScale;
}
//Movements.RemoveAt(MovementIndex);
}