我正在联合开发 3d 篮球比赛。
它有一个分数和一个计时器。一段时间后,我的场景加载并从头开始。每次我扔球时,我都必须生成它。
它有一个生成按钮和一个射击按钮。但我不想使用生成按钮。所以我想自动生成球。
我应该怎么做?我在下面给出了生成按钮代码和抛出按钮代码。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnButton: MonoBehaviour
{
public GameObject ball;
public GameObject BallPosition;
public void Spawn()
{
ball.transform.position = BallPosition.transform.position;
var ballPosition = ball.transform.position;
ball.GetComponent<Rigidbody>().useGravity = false;
ball.GetComponent<Rigidbody>().velocity = Vector3.zero;
ball.transform.position = ballPosition;
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ThrowButton: MonoBehaviour
{
static Animator anim;
public GameObject ball;
public float ballThrowingForce = 5f;
internal bool holdingBall;
void Start()
{
anim = GetComponent<Animator>();
ball.GetComponent<Rigidbody>().useGravity = false;
}
public void Throw()
{
anim.SetTrigger("isThrowing");
StartCoroutine(Test());
}
IEnumerator Test()
{
yield return new WaitForSeconds(1.5f);
ball.GetComponent<Rigidbody>().useGravity = true;
//ball.GetComponent<Rigidbody>().AddForce(transform.up * ballThrowingForce);
ball.GetComponent<Rigidbody>().AddForce(0, 380.0f, ballThrowingForce);
}
}
最佳答案
要生成一个球,您应该创建一个预制件并将其实例化。示例:
private class Spawner : MonoBehaviour
{
public GameObject prefab;
public GameObject Spawn() => Instantiate(prefab);
}
这样你的 throw 代码应该产生一个球,如果你想摧毁一个旧的球。
关于c# - 如何在 Unity 中重生对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59343202/