我正试着在游戏中随着分数的上升而缩放预制件。我试着在预制件本身添加一个简单的比例脚本,它起作用了。不过,它只对已经刷新出来的预制件进行缩放,后面继续刷新出来的预制件,依旧保持原来的大小。因此,我将脚本从预制件中删除,并将代码放入对象生成器中。
我把这个脚本放在update函数中,试图让对象按比例缩放。
if (currentScore >= recScore && objectScale == false)
{
objectScale = true;
if (objectScale == true)
{
objects.transform.localScale += new Vector3(-0.1f, -0.1f, -0.1f);
}
if (currentScore == 0)
{
objectScale = false;
}
}
问题是对象的“对象”。transform.localscale在“spawn”函数中,我不确定如何在更新中访问它。
所以,然后我试图像这样在spawn函数中添加代码,但这对我没有任何帮助。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectSpawn : MonoBehaviour
{
[SerializeField]
float[] percentages;
public GameObject[] prefab;
public float spawnRate = 1f;
public float minHeight = -1f;
public float maxHeight = 1f;
public int recScore = 3;
private int currentScore;
private bool objectScale = false;
private bool spawnPointPosition = false;
private float resetSpawnPoint;
private void OnEnable()
{
InvokeRepeating(nameof(Spawn), spawnRate, spawnRate);
}
private void OnDisable()
{
CancelInvoke(nameof(Spawn));
}
private void Spawn()
{
GameObject objects = Instantiate(prefab[GetRandomSpawn()], transform.position,
Quaternion.identity);
objects.transform.position += Vector3.up * Random.Range(minHeight, maxHeight);
objects.transform.SetParent(transform);
if (currentScore >= recScore && objectScale == false)
{
objectScale = true;
if (objectScale == true)
{
objects.transform.localScale += new Vector3(-0.1f, -0.1f, -0.1f);
}
if (currentScore == 0)
{
objectScale = false;
}
}
}
private int GetRandomSpawn()
{
float random = Random.Range(0f, 1f);
float numForAdding = 0;
float total = 0;
for(int i = 0; i < percentages.Length; i++)
{
total += percentages[i];
}
for(int i =0; i < prefab.Length; i++)
{
if (percentages[i] / total + numForAdding >= random)
{
return i;
}
else
{
numForAdding += percentages[i] / total;
}
}
return 0;
}
private void Update()
{
currentScore = GameManager.gameManager.repeatScore;
resetSpawnPoint = GameManager.gameManager.score;
if (currentScore >= recScore && spawnPointPosition == false)
{
spawnPointPosition = true;
if (spawnPointPosition == true)
{
gameObject.transform.position += new Vector3(0f, 0f, 0f);
}
}
if (currentScore == 0)
{
spawnPointPosition = false;
}
if (resetSpawnPoint == 0)
{
gameObject.transform.position = new Vector3(20f, 0f, 0f);
}
}
}
我想知道,是否有可能在更新中访问spawn函数中的“对象”,以便在预制件生成之前在内部对其进行缩放?
1条答案
按热度按时间lh80um4z1#
这应该是可能的:
编辑:我引入了一个单独的方法,称为
ScaleSpawnedObject()
,它将衍生对象的比例乘以缩小因子。调整reductionFactor
值以控制缩放效果。当Spawn()
函数中满足评分条件时,调用此方法。