我正在实例化带有RectTransform组件和个人脚本(某些Monobehaviour)的预制件。
我完全可以将此实例化的预制件作为所需的GameObject的父级,甚至可以设置其localPosition.x值和localPosition.z值,但不能设置其Y值。
目标是实例化此预制件,并对其进行实例化,然后用一个新的实例进行重复。
旧的预制件应向上移动,以便让新的实例代替它。
我可以更改其localPosition X和Z值,如(1234,y,5678),但Y保持为0。始终。
这是代码:
脚本A:https://pastebin.com/Q5jqy6rz
脚本B:https://pastebin.com/64sChs3S
注意。每个实例都作为其父对象的GameObject仅具有RectTransform组件,Image组件,Script A和CanvasRenderer组件。
/*Script A, this is part of the script were I instantiate the game object*/
/*Fields:*/
private LineTPA CurrentLine; //last Line created
private List<LineTPA> listLinesTPA; //Where I keep reference to each line created.
[Serializedfield] GameObject PrefabLineTPA; //Ref to the prefab I'm instantiating.
//Position where I want each new Line to be:
private Vector3 StartPosition = new Vector3 (someX, someY, someZ);
/*Methods: */
private void CreateNewLine()
{
//Instantiating:
GameObject GOinstance= Instantiate(PrefabLineTPA);
GOinstance.transform.SetParent(this.transform, worldPositionStays:false);
//Getting the Monobehaviour from the GameObject:
CurrentLine = GOinstance.GetComponent<LineTPA>();
//Keeping a reference to the script for later.
listLinesTPA.Add(CurrentLine);
//The script needs some parameters to start working.
CurrentLine.InitiateMe(/*some parameters*/);
//Placing the object in the position that I want.
CurrentLine.MyPosition= StartPosition;
//It gets the X and Z, but the Y stays on 0.
}
private void CreateSpaceForNewLine()
{
foreach(LineTPA line in listLineTPA)
{
line.MoveUp();
}
}
/*Script B, this is part of the LineTPA script, it's a component on the Prefab. */
//In the prefab, this field is given through the editor:
public RectTransform rectTransform;
//Just some shorthand props:
public Vector3 MyPosition
{
get => rectTransform.localPosition;
set => rectTransform.localPosition = value;
}
public float MyHeight => rectTransform.rect.height;
//-----------------------------------------------------
public void InitiateMe(/*some parameters*/)
{
/*gets references for some stuff*/
}
/// <summary>
/// Called from ScriptA.
/// </summary>
public void MoveUp()
{
float sameX = MyPosition.x;
float sameZ= MyPosition.z;
//Here's where I try to change the Y position
float newY = MyPosition.y + MyHeight ;
//-------------------------------------------
MyPosition = new Vector3(sameX , newY, sameZ);
}
任何帮助将不胜感激。
答案 0 :(得分:0)
好吧,我最终添加了VerticalLayoutGroup组件(如@derHugo的建议),它完成了工作。我不知道为什么只有Y值没有变化。
编辑:之所以不能更改游戏对象的rectTransform是因为我的动画控制器。