mortis20
mortis20

Reputation: 27

Making a gameobject disappear when i'm certain distance from it

I created a village in Unity, but it is really high quality, so I had performance issues.

I did occlusion baking and managed to improve it a bit. But Unity keeps "seeing" the village even if it has quite big walls and a lot of trees between me and the village.

I tried to make the whole city disappear when I'm too far away and reappear when I'm getting closer.

I tried with this script but it doesn't work. (Script works on AI for detecting if I'm close enough to start following me)

EDIT:

How the gameObject looks in the hierarchy

How the gameObject looks

Inside are all the props divided in 3 other Gameobjects(plot=fence, and budynki=buildings and props=props
(miasto is the name of the gameobject in which all prefabs are, also I moved the playercontroller to this script so it should detect the player)

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

public class Miasto : MonoBehaviour
{
    public Transform player;
    public float LookRadius = 240f;
    void Start()
    {
        GetComponent<Miasto>().enabled = true;
    }

    void Update()
    {
            if (Vector3.Distance(player.position, this.transform.position) > 240)
            {
                GetComponent<Miasto>().enabled = false;
            }
            else
                GetComponent<Miasto>().enabled = true;
    }

    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(transform.position, LookRadius);
    }
}

Upvotes: 0

Views: 1595

Answers (2)

c_ure_sh
c_ure_sh

Reputation: 25

Try This, I disabled the meshRenderer which makes it visually dissapear:

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

public class Miastro : MonoBehaviour
{
    public Transform player;
    MeshRenderer[] meshRenderer;
    public float LookRadius = 240f;

    void Start()
    {
        GetComponent<Miastro>().enabled = true;
        meshRenderer = gameObject.GetComponentsInChildren<MeshRenderer>();
    }

    void Update()
    {
        if (Vector3.Distance(player.position, this.transform.position) > 240)
        {
            foreach (MeshRenderer renderer in meshRenderer) 
            {
                renderer.enabled = false;
            }
        }
        else 
        {
            foreach (MeshRenderer renderer in meshRenderer)
            {
                renderer.enabled = true;
            }
        }
    }

    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(transform.position, LookRadius);
    }
}

Upvotes: 3

Andrew Hartz
Andrew Hartz

Reputation: 133

You could make it an LOD object with only 2 levels your object and nothing.

Upvotes: 3

Related Questions