Home>

This is a Unity (C #) question.
I want to make a script that moves the slider and the object moves, but it doesn't work.
NullReferrence ~ error has occurred, so I think the cause is that the slider value could not be obtained, but I do not know how to get the slider value on the canvas from another object, so the slider from another object I would like to know how to get the value of. By the way, we are planning to use a rigid body force.

"Problem script" ↓

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

public class ForceControrl: MonoBehaviour
{
// RigidBody definition
public Rigidbody rigidbody;

// Slider definition
Slider slider;

void Start ()
{
rigidbody = this.GetComponent();
}

void Update ()
{
// Proceed (Force)
Vector3 force = new Vector3 (slider.value, 0, 0);
this.rigidbody.AddForce (force, ForceMode.Force);
}
}

  • Answer # 1

    As for the script mentioned first, it is not good to use a variable name as it is, such asRigidbody rigidbodySlider slider. If you can't use it, it will come out. I think that it is good to keep it within the range that can be understood by using a part likeRigidbody rig.

    Next is theSlider slider, but it is a defined but private variable, and no value is passed to the slider, so naturally it is empty when using the value. So it seems that a Null error has occurred.
    So make it a public variable and set the specified slider from the Inspector.

    Next aboutAddForce, even if you can refer to the value of Slider as it is, it does not have enough force to move the object. (When Ues Gravity is enabled, if it is disabled, a method of quiescing is required.)
    The reason is that the value obtained from Slider is in the range of0 to 1, so the value is simply small.
    So, add power by multiplying the value obtained from Slider by any number.

    A script that takes the above into account is as follows.
    ThepulsPowervalue can be adjusted with the slider from the Inspector, so try changing the value.

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;
    public class ForceControrl: MonoBehaviour
    {
        private Rigidbody rig;
        public Slider slide;
        [Range (1,10)]
        public float pulsPower;
        void Start ()
        {
            rig = this.GetComponent();
        }
        void Update ()
        {
            Vector3 force = new Vector3 (slide.value, 0, 0);
            rig.AddForce (force * pulsPower, ForceMode.Force);
        }
    }

Related articles