How to make the enemy invisible before it goes inside the vision of the player?

I am trying to make the Enemy invisible before he goes inside the player’s vision cone, once he becomes inside the vision cone it should be visible. In the start function I have added the following piece of code:

void Start() {	
        custRender = GetComponent<Renderer>();
        //Hide the target here
        custRender.enabled = false;
} 

and in FindVisibleTargets() function I modified it into custRender.enabled = true ; as follows:

	void FindVisibleTargets() {
		visibleTargets.Clear ();
		Collider[] targetsInViewRadius = Physics.OverlapSphere (transform.position, viewRadius, targetMask);

		for (int i = 0; i < targetsInViewRadius.Length; i++) {
			Transform target = targetsInViewRadius *.transform;*
  •  	Vector3 dirToTarget = (target.position - transform.position).normalized;*
    
  •  	if (Vector3.Angle (transform.forward, dirToTarget) < viewAngle / 2) {*
    
  •  		float dstToTarget = Vector3.Distance (transform.position, target.position);*
    
  •  		if (!Physics.Raycast (transform.position, dirToTarget, dstToTarget, obstacleMask)) {*
    

visibleTargets.Add(target);

//here to show the target
custRender.enabled = true;
}

  •  	}*
    
  •  }*
    
  • }*

In unity inspector, I assigned to the custRender variable the enemy object as shown in the screenshot below:
[206179-visioncone.png|206179] *

After implementing the code, the player has become invisible and the enemy is still visible. Any suggestions please to make the enemy invisible before it goes inside the player’s vision?
PLEASE LET ME KNOW IF YOU NEED THE WHOLE CODE.

Hi,
The problem is, on your first line you are setting players renderer to custRender which overrides what you set in the inspector. If you delete this line it will work.