Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

[SOLVED ] Problem with Line Renderer Positions?

Discussion in 'Scripting' started by Solado, Mar 29, 2019.

  1. Solado

    Solado

    Joined:
    Jun 11, 2014
    Posts:
    9
    Hi everyone,

    I am new to unity so bear with me on this.

    I have a strange issue with the Line Render function in unity, I am not sure how to get around this problem and have spent a while trying to work it out but seem to be getting no where. What I am trying to achieve is drawing a line between the "fire point" on the tower and the enemy position. This works fine if the Prefab of the tower is already in the scene but when I build an instantiated version that's when it all goes wrong.

    The left is the "play" screen, the green arrow is pointing to the built tower in the scene and the red arrow with the ?? is pointing to where the line is being drawn. The Blue circles are the "enemy" which is stored in a "target" gameobject.
    The prefab has an empty game object called "Fire Point" and the "lineRenderer" is a reference to the line renderer component attached to the tower.

    In short the line renderer isn't drawing a line in the correct place and it appears randomly in the scene view even though the positions are referenced correctly.



    Thank you if anyone can help me with this as I have been really struggling.

    Code (csharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. public class LaserTurret : MonoBehaviour
    7. {
    8.  
    9.  
    10.     private Transform target;
    11.      public float range = 15f;
    12.  
    13.     [Header("Use Bullets (Default)")]
    14.     public GameObject bulletPrefab;
    15.     public float fireRate = 1f;
    16.     private float fireCountdown = 0f;
    17.  
    18.     [Header("Use laser")]
    19.     public bool useLaser = false;
    20.     public LineRenderer lineRenderer;
    21.  
    22.     [Header("Setup Fields")]
    23.  
    24.     public string enemytag = "enemy";
    25.  
    26.     public Transform partToRotate;
    27.     public float turnSpeed = 10f;
    28.  
    29.  
    30.     public Transform firePoint;
    31.  
    32.  
    33.  
    34.     // Start is called before the first frame update
    35.     void Start()
    36.     {
    37.         InvokeRepeating("UpdateTarget", 0f, 0.5f);
    38.     }
    39.  
    40.     void UpdateTarget ()
    41.     {
    42.         GameObject[] enemies = GameObject.FindGameObjectsWithTag(enemytag);
    43.         float shortestDistance = Mathf.Infinity;
    44.         GameObject nearestEnemy = null;
    45.  
    46.         foreach (GameObject enemy in enemies)
    47.         {
    48.             float distanceToEnemy = Vector3.Distance(transform.position, enemy.transform.position);
    49.             if (distanceToEnemy < shortestDistance)
    50.             {
    51.                 shortestDistance = distanceToEnemy;
    52.                 nearestEnemy = enemy;
    53.             }
    54.         }
    55.  
    56.         if (nearestEnemy != null && shortestDistance <= range)
    57.         {
    58.             target = nearestEnemy.transform;
    59.         } else if ( nearestEnemy != null && shortestDistance > range )        {
    60.             target = null;
    61.         }
    62.     }
    63.  
    64.     // Update is called once per frame
    65.     void Update()
    66.     {
    67.         if ( target == null)
    68.         {
    69.             if(useLaser)
    70.             {
    71.                 if (lineRenderer.enabled)
    72.                     lineRenderer.enabled = false;
    73.             }
    74.             return;
    75.         }
    76.            
    77.  
    78.         LockOnTarget();
    79.  
    80.         if (useLaser)        {
    81.             laser();
    82.         }
    83.         else        {
    84.             if (fireCountdown <= 0f)
    85.             {
    86.                 Shoot();
    87.                 fireCountdown = 1f / fireRate;
    88.             }
    89.  
    90.             fireCountdown -= Time.deltaTime;
    91.         }
    92.  
    93.        
    94.     }
    95.  
    96.     void LockOnTarget()
    97.     {
    98.         Vector3 dir = target.position - transform.position;
    99.         Quaternion lookRotation = Quaternion.LookRotation(dir);
    100.         Vector3 rotation = Quaternion.Lerp(partToRotate.rotation, lookRotation, Time.deltaTime * turnSpeed).eulerAngles;
    101.         partToRotate.rotation = Quaternion.Euler(0f, rotation.y, 0f);
    102.     }
    103.  
    104.     void laser()    {
    105.         if (!lineRenderer.enabled)
    106.             lineRenderer.enabled = true;
    107.  
    108.  
    109.         lineRenderer.SetPosition(0, firePoint.position);
    110.         lineRenderer.SetPosition(1, target.position);
    111.     }
    112.  
    113.     void Shoot()
    114.     {
    115.        GameObject bulletGO = (GameObject)Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
    116.         Bullet bullet = bulletGO.GetComponent<Bullet>();
    117.  
    118.         if (bullet != null)
    119.             bullet.Seek(target);
    120.     }
    121.  
    122.     void OnDrawGizmosSelected()
    123.     {
    124.         Gizmos.color = Color.red;
    125.         Gizmos.DrawWireSphere(transform.position, range);
    126.     }
    127.  
    128. }
    129.  
     
  2. MD_Reptile

    MD_Reptile

    Joined:
    Jan 19, 2012
    Posts:
    2,664
    I am wondering what "FirePoint" gets assigned to?

    So you have that empty gameobject as a child to the tower prefabs themselves that gets saved into the prefab, but it might be a good idea to check what the "FirePoint.Position" actually is set as after the instantiation.

    I'd start with debugging there, and figure out why it gets set to something other than what your trying to set it to, then try to figure out the end point after that.
     
  3. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    Check if the line renderer is set to use world or local space.
     
  4. Solado

    Solado

    Joined:
    Jun 11, 2014
    Posts:
    9
    THANK YOU! Seriously, I can't believe it was that simple. Thank you!
     
    ROBYER1 likes this.
  5. zheyuanzhou

    zheyuanzhou

    Joined:
    Oct 29, 2017
    Posts:
    22
    WTF. I spend almost an hour check the LR component by mySelf and double-check the "0" and "1" position inside that component. I should Watch your reply first. TIme Saver and project Saver!!!!
     
    stellamocha and MoonJellyGames like this.
  6. asknavaneeth

    asknavaneeth

    Joined:
    Apr 22, 2020
    Posts:
    3
    wow thank you man it helped me a lot
     
  7. doubleiicrap

    doubleiicrap

    Joined:
    May 26, 2020
    Posts:
    1
    bruh i could have saved 3 hours of my life by checking a box
     
    Lorrak, ThunderSlash and maxxmudd like this.
  8. Kalikovision

    Kalikovision

    Joined:
    Nov 12, 2018
    Posts:
    1
    Another fun fact about the line renderer, straight from Unity's documentation:

    This method (SetPositions) is preferred to SetPosition when setting all positions, as it is more efficient to set all positions using a single command than to set each position individually. Note that positionCount must be called before SetPositions. Also SetPositions ignores points with indices beyond positionCount.

    So if you're trying to set line positions on the fly from a variable array/list, set positionCount first to your new array size and THEN call the SetPositions with your new array. This feels kind of dumb to me since it feels tailor made to a very specific situation, but just figured I'd add this in case it helps someone else.
     
  9. rzhao_unity791

    rzhao_unity791

    Joined:
    Nov 27, 2023
    Posts:
    1
    man your suggestion is even helping my out like 4 years later. I spend 4 fking hours debugging and found I could solve this by hitting that little button. THANK YOU!