Home>

In the code below, I want to apply some force to the object created by "Instantiate" at the bottom, but I'm having trouble getting it.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace CSharpScript
{
    public class UnkoDandou12: MonoBehaviour
    {
        ///<summary>
        /// bullet Prefab
        ///</summary>
        [SerializeField, Tooltip ("Bullet Prefab")]
        private GameObject bulletPrefab;
        ///<summary>
        /// barrel object
        ///</summary>
        [SerializeField, Tooltip ("barrel object")]
        private GameObject barrelObject;
        ///<summary>
        /// Location information for bullet generation
        ///</summary>
        private Vector3 instantiatePosition;
        ///<summary>
        /// bullet generation coordinates (read only)
        ///</summary>
        public Vector3 InstantiatePosition
        {
            get {return instantiatePosition;}
        }
        ///<summary>
        /// bullet speed
        ///</summary>
        [SerializeField, Range (1.0F, 20.0F), Tooltip ("shot ejection speed")]
        private float speed = 1.0F;
        ///<summary>
        /// bullet initial velocity
        ///</summary>
        private Vector3 shootVelocity;
        ///<summary>
        /// bullet initial velocity (read only)
        ///</summary>
        public Vector3 ShootVelocity
        {
            get {return shootVelocity;}
        }
        Camera Camera = Camera.main;
        Vector3 UnkoAngle;
        void Update ()
        {
            // Update the initial velocity of the bullet

            // Update bullet generation coordinates
            instantiatePosition = barrelObject.transform.position + new Vector3 (0f, 2.5f, 0f);
            // fire
            if (Input.GetKeyDown (KeyCode.Space))
            {
                // generate bullet and fly
                GameObject obj = Instantiate (bulletPrefab, instantiatePosition, Quaternion.identity) as GameObject;
                Rigidbody rid = obj.GetComponent<Rigidbody>();
                UnkoAngle = Camera.transform.rotation * new Vector3 (0f, 6f, 25f);
                rid.AddForce (UnkoAngle, ForceMode.Impulse);
                // disappear after 5 seconds
                Destroy (obj, 5.0F);
            }
        }
    }
}


I intend to put the generated object in "obj", but even if it is executed, the subsequent processing of obj's rigid body is not performed. This.

A rigid body is attached to the generated object.

  • Answer # 1

            Camera Camera = Camera.main;

    After trying it, I got the following error above.
    (You can check it from the Console window)

    UnityException: get_main is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead.Called from MonoBehaviour 'UnkoDandou12' on game object 'GameObject'.
    See "Script Serialization" page in the Unity Manual for further details.
    CSharpScript.UnkoDandou12..ctor () (at Assets/UnkoDandou12.cs: 52)

    Also, a NullReferenceException was thrown apart from this (line 70).
    From the above, the variable Camera may be null (because it's not normal).
    If an error occurs, it will not be executed after that (except a part), so this is the cause.

    If you substitute Awake () or Start () instead of substituting Camera.main as the initial value according to the content of the error, I think that it will work normally.
    Although not related to the question, if the same name as the class causes a bug, it is better to change the variable name from Camera as well.

    Also, please check for errors in the future.
    Checking the error is almost essential for programming, and should be included when asking a question.