【发布时间】:2017-12-01 18:53:54
【问题描述】:
我正在尝试复制 Zelda 健康系统。代码看起来非常好并且工作正常。
但是心脏容器放错了。它们在画布下方被实例化。
这是重要的代码,心脏容器是正确的,只是在错误的位置。
x 和 y 的计算是正确的,但在画布上却不是。
private Transform healthBar = GameObject.FindGameObjectWithTag("HealthController").transform; // container for the heartContainers
private GameObject healthWrapperObject = Resources.Load("HealthContainer") as GameObject; // the backgroundImage and parent of the heart
private List<Image> healthContainers = new List<Image>(); // list of hearts for later usages
private int maxHealth = 6;
private int currentHealth;
private int healthPerHealthContainer = 4; // 4 lifepoints per heart
private int healthContainersPerRow = 5; // 5 hearts per row
private int healthContainerStartPositionX = 0; // Healthbar starts at 0 on x
private int healthContainerStartPositionY = 0; // Healthbar starts at 0 on y
private int healthContainerSpacingX = 10; // horizontal spacing
private int healthContainerSpacingY = -10; // vertical spacing
private void Start()
{
currentHealth = maxHealth;
InitializeHealthBar();
}
public void InitializeHealthBar()
{
int neededHealthContainers = maxHealth % healthPerHealthContainer == 0 ? maxHealth / healthPerHealthContainer : maxHealth / healthPerHealthContainer + 1; // Calculate the needed container count
int counter = 0; // counts the hearts per row
int x = healthContainerStartPositionX; // horizontal position of the heartContainer
int y = healthContainerStartPositionY; // vertical position of the heartContainer
for (int i = 0; i < neededHealthContainers; i++)
{
counter++;
if (counter >= healthContainersPerRow) // start a new line after 5 hearts per row
{
x = healthContainerStartPositionX; // move back to the left
y += healthContainerSpacingY; // go for the next line
counter = 0; // reset the counter
}
else
x += healthContainerSpacingX; // place the new container right next to the previous
Transform newHealthContainerTransform = Instantiate(healthWrapperObject, new Vector2(x, y), healthWrapperObject.transform.rotation).transform; // create the healthContainer parent / backgroundImage
newHealthContainerTransform.SetParent(healthBar); // take the container and make it a child of the healthBar
healthContainers.Add(newHealthContainerTransform.GetChild(0).GetComponent<Image>()); // get the heart of the heartContainer and add it to the heartList
}
}
我为 healthBar、healthContainer / backgroundImage 和 heart(“healthfill”)添加了转换设置。
在所有 3 个元素上,我按下了 Strg+Alt 和 Shift 来锚定它们。
heartcontainer 应该被添加到 healthbar 中,heart 是 heartcontainer 的子级并且被设置为可以拉伸(它应该和它的父级一样大小)
为什么 UI 预制对象在画布下方实例化?
【问题讨论】:
-
抱歉,我不能提供更多帮助,但是您是否考虑过在统一论坛中提出这个问题?不禁觉得这可能是这类问题的错误地方......:/
-
嗯不,其实我没有..
-
不用担心。我不会对您投反对票或其他任何事情,只是认为您最好在更具体的论坛上过得更好。祝你好运! :)
-
谢谢你,我真的希望有人对我有想法
-
这个问题在这里有效。问题是什么,问题是什么?我想这就是为什么你还没有任何答案。
标签: c# user-interface unity3d