Home > Blockchain >  Cannot freeze player rotation from script
Cannot freeze player rotation from script

Time:11-01

I am trying to unfreeze my player rotation and then freeze it again. It unfreezes but due to some reason I cannot freeze the rotation again.

GameManager script -

    public void enableRotation()
    {
        if (CompareTag("Player"))
        {
            rb.freezeRotation = true;
        }


    }

flyer_Off script -

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

public class flyer_Off : MonoBehaviour
{
    void OnTriggerEnter(Collider other)
    {
        FindObjectOfType<GameManager>().enableRotation();
    }

}

I was able to unfreeze rotation the same way but for some reason it's not working when I try to freeze it again.

I tried adding the GameManager script to Player and flyer_Off to cube with box collider on trigger and player as well.

I can add if anymore info is needed.

Thank you

CodePudding user response:

Since you wanted to freeze the rotation, it should work. Only exception would be not reaching that line at all. Please check if your object has the tag "Player" and indeed has a "GameManager" component on it.

Setting the freeze value to true rb.freezeRotation = true; only freezes it. I would rename the function to "toggleRotation" and do this instead: rb.freezeRotation = !rb.freezeRotation;

CodePudding user response:

You should access the player with Collider other.

void OnTriggerEnter(Collider other)
{
    if (CompareTag("Player"))
    {
        RigidBody rb = other.gameObject.GetComponent<RigidBody>();
        rb.freezeRotation = true;
    }
}

As derHugo said. Your GameManager probably should not have a RigidBody of your player. The player is responsible for its own RigidBody.

Please consider:

[RequiredComponent(typeof(RigidBody))]
public class Player : MonoBehaviour
{

    public void EnableRotation()
    {
        
        RigidBody rb = gameObject.GetComponent<RigidBody>();
        rb.freezeRotation = true;
        
    }

}

public class flyer_Off : MonoBehaviour
{

    void OnTriggerEnter(Collider other)
    {

        // if other.gameObject does not contain a component Player, it returns null
        Player player = other.GetComponent<Player>();
        if(player)
        {

             player.EnableRotation();

        }

    }

}

Having a member function called EnableRotation and then within that function freezing the rotation doesn't make it easier to maintain the code.

  • Related