How to Change Game Object Component Variable

I’m sure there is a fairly easy solution to this but I have looked and not found a good explanation.

Script one is on my FirstPersonController

[SerializeField] public MouseLook m_MouseLook;

Script 2

gameObject.GetComponent<MouseLook>().XSensitivity = 2;
gameObject.GetComponent<MouseLook>().YSensitivity = 2;
gameObject.GetComponent<MouseLook>().lockCursor = true;

so I tried this and learned I need to edit a variable of a component and MousLook is not a component.
How do I change variables of MouseLook?

Sorry I’m really new to C# and am not sure how to do this.

I don’t know how else to change things. I thought below would work but no.

MouseLook.XSensitivity = 0

When I tried with getcomponent visual studio recognized XSensitivity, YSensitivity, and lockCursor.
but when I do MouseLook. there are no options. Mouse look is public.

I’m so confused.
I just want to edit the fields for mouse look. Any suggestions or help would be so appreciated.

Well it depends where that variable m_MouseLook is defined, if its in the first person controller, then you’d need to do

gameObject.GetComponent<FirstPersonController>().m_MouseLook - but that sounds unlikely, Im guessing m_MouseLook is possibly something locally in your own script…

If MouseLook is a class(/component) its unlikely MouseLook.<something> is a valid option it would need to be static.

So, if MouseLook is a class, the m_MouseLook could be the answer, but you cant just have a box shaped MouseLook called m_MouseLook you would need to populate it, so perhaps m_MouseLook = gameObject.GetComponent<FirstPersonController>().MouseLookl; then you can do m_MouseLook.XSensitivity=2; perhaps. but hey, with info provided too many open questions and not enough info provided

Thank you so much for taking the time to comment and help! I greatly appreciate it I’v been stuck for a couple days now.

FPScontroller is my game object, FirstPersonController is my component and Mouse Look is under that. I’m trying to change FirstPersonController variables from within my inventory script. Basically Im trying to unlock cursor and lock movement when inventory is opened. No matter what I try I cant seem to access these variables. The inventory script is also on the gameobject FPScontroller.

if I could disable and re-enable FirstPersonController that would be the perfect solution

I tried

gameObject.GetComponent<FirstPersonController>().enabled = false;

but nothing happenes.

If MouseLook is a property of the FirstPersonController component, then you need a reference to the component first, before you can access its respective properties.

So you would GetComponent<FirstPersonController>(), not for MouseLook (which will be logging a warning about using an invalid type in GetComponent<T>). Then you can access its .MouseLook property (I’m assuming the name here).

Of course you need to be using GetComponent<T> with a reference to the game object that actually has this component. If this is happening on a component on the same game object, then just serialize a reference directly to said component via the inspector.

Well.

Should possibly work

I’m stumped. I even tried

GameObject.Find("Player").GetComponent<FirstPersonController>().enabled = false;

and still no go. I have to be missing something really silly.
I checked with visual studio, it only wants “enabled”.

You do need to describe what particularly isn’t working. Does it throw an error? Does the component’s enabled state not change (confirmed via the inspector)?

Can you just directly reference the player?

stop finding, and getting components, its incredibly unnecerssary, especially as you know (otherwise you’d have had null excerption the first time) you’re on the game object with the controller

Please learn to cache the components and objects, your code, players and the peoples sanity will happier

As Ive just seen what behavior are you expecting when you change enabled to false?

So I’m expecting:

gameObject.GetComponent().enabled = false;
to disable my firstpersoncontroller script when my player presses I

void Update()
{
    UpdateHPBar();
    currentHealth -= Time.deltaTime * 0.1f;

    if  (currentHealth < 0) gameOver.SetActive(true);


    if (Input.GetKeyDown(inputManagerDatabase.CharacterSystemKeyCode))
    {
        if (!characterSystem.activeSelf)
        {
            characterSystemInventory.openInventory();
        }
        else
        {
            if (toolTip != null)
                toolTip.deactivateTooltip();
            characterSystemInventory.closeInventory();
        }
    }

    if (Input.GetKeyDown(inputManagerDatabase.InventoryKeyCode))
    {
        if (!inventory.activeSelf)
        {
            mainInventory.openInventory();
            //gameObject.SetActive(false);
            invBacking.SetActive(true);
            
            //gameObject.GetComponent<FirstPersonController>().enabled = false;
            GameObject.Find("Player").GetComponent<FirstPersonController>().enabled = false;




        }
        else
        {
            if (toolTip != null)
                toolTip.deactivateTooltip();
            mainInventory.closeInventory();
            //gameObject.SetActive(true);
            invBacking.SetActive(false);

           //gameObject.GetComponent<FirstPersonController>().enabled = true;
            GameObject.Find("Player").GetComponent<FirstPersonController>().enabled = true;





        }
    }

    if (Input.GetKeyDown(inputManagerDatabase.CraftSystemKeyCode))
    {
        if (!craftSystem.activeSelf)
            craftSystemInventory.openInventory();
        else
        {
            if (cS != null)
                cS.backToInventory();
            if (toolTip != null)
                toolTip.deactivateTooltip();
            craftSystemInventory.closeInventory();
        }
    }


}

I did get an error!!
Capture

thats playerinventory though, thats nothing to do with this

Correct, I’m wanting to disable FPS controller from Inventory script. This inventory script is on the same game object fpscontroller script is on (player)

Yeah this is why you should also keep the Console open, and pay attention to the errors you get.

Nonetheless writing code like this:

GameObject.Find("Player").GetComponent<FirstPersonController>().enabled = false;

Is a bad idea. As the null-reference could be happening in two different places here.

You probably want code to inform you of errors so you know more precisely what is going wrong:

var playerGO = GameObject.Find("Player");
if (playerGO != null)
{
	if (playerGO.TryGetComponent(out FirstPersonController fpsController) == true)
	{
		fpsController.enabled = false;
	}
	else
	{
		Debug.LogError("Player Game object does not have FirstPersonController component.");
	}
}
else
{
	Debug.LogError("Cannot find player game object");
}

Nonetheless you don’t want to be using GameObject.Find or similar.

I’ll ask again, can you directly reference this component via the inspector?

I’m sorry Spiney Im not exactly sure what you mean.

Serialize a field of type FirstPersonController, and assign the reference via the inspector. Probably the most fundamental thing you can do in Unity.

[SerializeField]
private FirstPersonController _fpsController; // assign via inspector

Ok, I added this to the top of my script, but now I’m running into a different issue. “FPSController” will not slot into the space via inspector. I ran into this issue before and still have not figured out why my FPSController will not slot into those fields. It feels like a serious handicap.

Well there are certain situations where you can’t assign a reference.

Namely you cannot:

  • Assign a reference across two scenes
  • Assign a reference from a project asset to a scene asset

Or of course you’re serializing a field of the wrong type, or you’re dragging the wrong game object/component.

I finally managed to solve my issue. I was able to add my FPS game object as a game object rather than a controller.

public GameObject FPS;

I then renamed and reclassed my FirstPersonController to FPSController.

I was then able to do

if (Input.GetKeyDown(inputManagerDatabase.InventoryKeyCode))
{
    if (!inventory.activeSelf)
    {
        mainInventory.openInventory();
        //gameObject.SetActive(false);
        invBacking.SetActive(true);
        FPS.GetComponent<FPSController>().enabled = false;
        




    }
    else
    {
        if (toolTip != null)
            toolTip.deactivateTooltip();
        mainInventory.closeInventory();
        //gameObject.SetActive(true);
        invBacking.SetActive(false);
        FPS.GetComponent<FPSController>().enabled = true;






    }
}

Thank you so much for all the help, we got there.