简体   繁体   English

Unity3D 在 c# 重生相机的问题

[英]Problem with respawned camera in Unity3D in c#

I have a problem with camera in Unity.我在 Unity 中遇到相机问题。 I want to follow to the ball.我想跟上球。 I want to make auto respawn for the ball and camera.我想让球和相机自动重生。 But the code works but camera doesn't follow to the ball.但是代码有效,但相机没有跟随球。 This is code for auto respawn:这是自动重生的代码:

public class start : MonoBehaviour
{
public GameObject Camera;
public GameObject Ball;
void Start()
{
    GameObject ball = GameObject.Instantiate(Ball);
    Ball.name = "Ball";
    ball.transform.position = transform.position + Vector3.up * 0.5f;
    Instantiate(Camera);
    Camera.name = "Camera";
    Camera.transform.position = transform.position + new Vector3(0.25f, 1.75f, 6.5f);
}

The code for camera controller:摄像头controller的代码:

public Transform Ball;
void Update()
{
    Rigidbody rigidbody = Ball.GetComponent<Rigidbody>();
    float ballVelocity = rigidbody.velocity.sqrMagnitude;

    UnityEngine.Vector3 vector = new UnityEngine.Vector3(0, 4, 7);
    vector *= (1+ ballVelocity / 30);
    UnityEngine.Vector3 nowaPozycjaKamery = Ball.position + vector;
    transform.position = UnityEngine.Vector3.Lerp(transform.position, nowaPozycjaKamery, Time.deltaTime*5);
    transform.LookAt(Ball);
}

Camera worked well before auto respawn.相机在自动重生前运行良好。 Code work that on start camera follow to good position, but is freezed when the ball change the position.启动相机时的代码工作遵循良好的 position,但当球改变 position 时被冻结。

I wish you provided more information on this question.我希望你提供更多关于这个问题的信息。 Like is there any NullReferenceException or other exceptions.就像是否有任何 NullReferenceException 或其他异常。 But I'll try to answer your issue anyways.但无论如何我都会尽力回答你的问题。 I think the problem is that the camera script doesn't have the reference to the new ball that's being spawned (this is in the case of destroying the old ball and Instantiating a new one with Destroy(gameObject) ).我认为问题在于相机脚本没有对正在生成的新球的引用(这是在销毁旧球并使用Destroy(gameObject)实例化新球的情况下)。

What I suggest is to add a Method in the camera script that will be in charge of injecting the new ball into the script.我的建议是在相机脚本中添加一个方法,负责将新球注入脚本。 And then you call this method with the new spawned ball in the script responsible for spawning.然后在负责生成的脚本中使用新生成的球调用此方法。 Or a more straightforward but not efficient way is to check if the ball property is null and then you make a call to GameObject.Find("Name of The ball object") and you give the name of the ball object.或者更直接但效率不高的方法是检查球属性是否为 null,然后调用 GameObject.Find ("Name of The ball object")并给出球的名称 object。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM