unity – Why the objects are moving to the first moving object instead moving on the waypoints?

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

public class Waypoints : MonoBehaviour
{
    public List<Transform> objectsToMove;
    public LineRenderer lineRenderer;
    public float speed;
    public bool go = false;
    public bool moveToFirstPositionOnStart = false;
    public float rotSpeed;
    public bool random = false;
    public int currentCurvedLinePointIndex;

    private Vector3() positions;
    private Vector3() pos;
    private int index = 0;
    private bool goForward = true;
    private List<GameObject> curvedLinePoints = new List<GameObject>();
    private int numofposbetweenpoints;
    private bool getPositions = false;
    int randomIndex;
    int curvedPointsIndex;
    public float delay;
    private float() startTimes;

    // Start is called before the first frame update
    void Start()
    {
        for (int i = 0; i < objectsToMove.Count; i++)
        {
            var parent = GameObject.Find("Moving Object Parent");
            objectsToMove(i) = Instantiate(objectsToMove(i), parent.transform);
            objectsToMove(i).name = "Platfrom";

            curvedLinePoints = GameObject.FindGameObjectsWithTag("Curved Line Point").ToList();

            if (curvedLinePoints != null && curvedLinePoints.Count > 0)
            {
                objectsToMove(i).rotation = curvedLinePoints(1).transform.rotation;
            }
        }

        startTimes = new float(objectsToMove.Count);

        for (int i = 0; i < startTimes.Length; i++)
        {
            startTimes(i) = Time.time + (Random.value * delay);
        }
    }

    Vector3() GetLinePointsInWorldSpace()
    {
        positions = new Vector3(lineRenderer.positionCount);
        //Get the positions which are shown in the inspector 
        lineRenderer.GetPositions(positions);


        //the points returned are in world space
        return positions;
    }

    // Update is called once per frame
    void Update()
    {
        

        if (lineRenderer.positionCount > 0 && getPositions == false && CurvedLineRenderer.linesSet)
        {
            pos = GetLinePointsInWorldSpace();
            numofposbetweenpoints = curvedLinePoints.Count;

            if (moveToFirstPositionOnStart == true)
            {
                foreach (Transform objToMove in objectsToMove)
                {
                    objToMove.position = pos(index);
                }
            }

            getPositions = true;
        }

        if (go == true && lineRenderer.positionCount > 0)
        {
            Move();
        }
    }

    int counter = 0;
    int c = 1;
    void Move()
    {
        for (int i = 0; i < objectsToMove.Count; i++)
        {
            if (Time.time < startTimes(i)) continue;

            Vector3 newPos = objectsToMove(i).position;
            float distanceToTravel = speed * Time.deltaTime;

            bool stillTraveling = true;
            while (stillTraveling)
            {
                Vector3 oldPos = newPos;

                newPos = Vector3.MoveTowards(oldPos, pos(index), distanceToTravel);

                distanceToTravel -= Vector3.Distance(newPos, oldPos);
                if (newPos == pos(index)) // Vector3 comparison is approximate so this is ok
                {
                    // when you hit a waypoint:
                    if (goForward)
                    {
                        bool atLastOne = index >= pos.Length - 1;
                        if (!atLastOne)
                        {
                            index++;
                            counter++;
                            if (counter == numofposbetweenpoints)
                            {
                                c++;

                                counter = 0;
                            }
                            if (c == curvedLinePoints.Count - 1)
                            {
                                c = 0;
                            }
                        }
                        else { index--; goForward = false; }
                    }
                    else
                    { // going backwards:
                        bool atFirstOne = index <= 0;
                        if (!atFirstOne)
                        {
                            index--;

                            counter++;
                            if (counter == numofposbetweenpoints)
                            {
                                c++;

                                counter = 0;
                            }
                            if (c == curvedLinePoints.Count - 1)
                            {
                                c = 0;
                            }
                        }
                        else { index++; goForward = true; }
                    }
                }
                else
                {
                    stillTraveling = false;
                }
            }

            objectsToMove(i).position = newPos;
        }
    }
}

For example, I have 3 objects to move. The first one start moving after 5 seconds and moving on the pos array positions.

Then the second object is start moving after 7 seconds but now instead moving also on the pos array positions the second object is reaching the first moving object and then move with him together.

The same thing happens with the last third object to move from the List objectsToMove.

I can’t figure out why they are reaching the first object that move instead that each one will move on the pos array positions ?

Not sure if it’s the delay line inside the Move function that make the problem :

if (Time.time < startTimes(i)) continue;

Or maybe the loop in the Move function :

for (int i = 0; i < objectsToMove.Count; i++)

Unity update sizeDelta in OnValidate based on Layout Group computed values

I’m trying to update the sizeDelta of a RectTransform in OnValidate. I’m trying to grab the computed values from a Layout Group.

Here’s what I’ve got:

#if UNITY_EDITOR
        void OnValidate()
        {
            UnityEditor.EditorApplication.delayCall += Resize;
        }

        private void Resize()
        {
            if (this == null) return;
            RectTransform parentRect = (RectTransform)gameObject.transform;
            RectTransform textRect = (RectTransform)tabText.transform;
            textRect.sizeDelta = new Vector2(parentRect.rect.height, parentRect.rect.width);
            layoutElement.preferredHeight = parentRect.rect.height;
        }
#endif

At first this seemed to be working, but it only works the first time OnValidate runs. Subsequence invocations of Resize() sets the sizeDelta to Vector2(0, 0).

I’m wondering what causes this and if there’s a way to avoid it. If I remove the delayCall, the values are correct, but I get warnings:

SendMessage cannot be called during Awake, CheckConsistency, or
OnValidate

I’d like to do this at edit time since there’s no need to compute this stuff at runtime.

unity – Parameter ‘Walk’ doesn’t exist?

I’m trying to make walk animation. But when I try to change animation idle to walk, ıt doesn’t work.
It says ‘Parameter “Walk” doesn’t exist’but I added parameter and script works. I can manually change parameter and it works(walk animation is playing). But when I try to change via script, ıt doesn’t work.

enter image description here

Here are codes

public class Controller : MonoBehaviour




private Rigidbody rb;

private float xPos;

Vector3 playerMovement;

(SerializeField) Animator anim;





private void Awake() => rb = GetComponent<Rigidbody>();

private void Start()
{

    
    xPos = transform.position.x;

}








// Update is called once per frame
void Update()
{
    Move();
    
}

private void Move()
{
    
    float mH = Input.GetAxis("Horizontal");

     playerMovement = new Vector3(0, 0, mH);

    rb.AddForce(playerMovement * 2f);

    anim.SetFloat("Walk", 1);

    transform.position = new Vector3(xPos, transform.position.y, transform.position.z);
    

}

unity – Character controller falling with positive speed

I’m having very weird problems with my player’s vertical movement. I’m using a Character Controller component with a capsule collider and no rigidbody. For testing purposes, I’ve ended reducing my jump script to just this line:

    owner.CharacterController.Move(new Vector3(0, 0.01f, 0));

When executing this script, the player should just fly upwards at a constant speed, right? Well, what ends up happening is that the player starts jumping in place repeatedly. The jumps are smooth, as if the movement was being affected by gravity. I thought that the standard Character Controller doesn’t handle gravity automatically and you have to do it yourself, so I can’t understand what’s going on here. There is no other code affecting the player, if I comment that line it just rests in place. If I try a different direction (like (0.01f, 0, 0)) the player moves in a straight line in the provided direction as expected. But when moving vertically, weird stuff happens :S

c# – Unity smooth local rotation around one Axis, oriented toward a target

Using the trick discussed in a similar question here and also here, we can define a helper method to point our local Y axis exactly in a particular direction, while turning our local Z axis to face (as close as possible) toward another direction.

Quaternion TurretLookRotation(Vector3 approximateForward, Vector3 exactUp)
{
    Quaternion rotateZToUp = Quaternion.LookRotation(exactUp, -approximateForward);
    Quaternion rotateYToZ = Quaternion.Euler(90f, 0f, 0f);

    return rotateZToUp * rotateYToZ;
}

Now we can use that in Update to face toward our target:

void Update() {
    // Form the direction we want to look towards
    Vector3 offsetToTarget = target.position - transform.position;

    // Preserve our current up direction
    // (or you could calculate this as the direction away from the planet's center)
    Vector3 up = transform.up;

    // Form a rotation facing the desired direction while keeping our
    // local up vector exactly matching the current up direction.
    Quaternion desiredOrientation = TurretLookRotation(offsetToTarget, up);

    // Move toward that rotation at a controlled, even speed regardless of framerate.
    transform.rotation = Quaternion.RotateTowards(
                            transform.rotation,
                            desiredOrientation,
                            maxDegreesPerSecond * Time.deltaTime
                         );

}

textures – Issue with Texture2D memory leak in Unity

I have a simple method that converts RenderTexture data into Texture2D

public static Texture2D RenderTextureToTexture2D(RenderTexture renderTexture, int width, int height,
    TextureFormat textureFormat = TextureFormat.RGB24, bool mipChain = false) {
    
    Texture2D tex = new Texture2D(width, height, textureFormat, mipChain);
    RenderTexture.active = renderTexture;
    
    tex.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
    tex.Apply();
    
    RenderTexture.active = null;
    // Here I want some way to release memory occupied by tex
    return tex;
}

The above mentioned method is working exactly as intended. However, if I call this method multiple times, or in update it starts using so much memory
Profiller

How can I avoid this problem?

c# – Erro “NullReferenceException: Object reference not set to an instance of an object” no Unity

Opa, estou tentando desenvolver o meu primeiro jogo com Unity, um Space Invaders, e até que consegui fazer bastante coisa, mas ao chegar na parte do código de criar o movimento do inimigo, estou recebendo esse erro:

NullReferenceException: Object reference not set to an instance of an object
EnemyController.Start () (at Assets/Scripts/EnemyController.cs:32)

Procurei bastante, mas não achei nenhuma resposta que pudesse ajudar no meu caso, então preciso de uma luz.

O problema fica na linha 32, essa aqui:
“InvokeRepeating(“MoveEnemy”, 0.1f, 0.3f);”

Código abaixo:

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

public class EnemyController : MonoBehaviour
{
    private Transform enemyHolder;
    public float speed;

    public GameObject shot;
    public Text winText;
    public float fireRate = 0.997f;

    void Start()
    {
        winText.enabled = false;
        InvokeRepeating("MoveEnemy", 0.1f, 0.3f);
        enemyHolder = GetComponent<Transform> ();
    }

    void MoveEnemy()
    {
        enemyHolder.position += Vector3.right * speed;

        foreach(Transform enemy in enemyHolder)
        {
            if(enemy.position.x < -10.5 || enemy.position.x > 10.5)
            {
                speed = -speed;
                enemyHolder.position += Vector3.down * 0.5f;
                return;
            }

            if(Random.value > fireRate)
            {
                Instantiate(shot, enemy.position, enemy.rotation);
            }

            if(enemy.position.y <= -4)
            {
                GameOver.isPlayerDead = true;
                Time.timeScale = 0;
            }

        }

        if(enemyHolder.childCount == 1)
        {
            CancelInvoke();
            InvokeRepeating("MoveEnemy", 0.1f, 0.25f);
        }
        
        if (enemyHolder.childCount == 0)
        {
            winText.enabled = true;
        }
    }
}

Why is my Post Processing not working? (Unity with URP)

I’m trying to get Post Processing working in my Unity Project, with URP enabled, but I’m not seeing it work. I’ve looked at a few tutorials and I’ve followed them exactly, but I never see any post processing happen.

Here’s the inspector window for my Camera:

enter image description here

And here’s the inspector window for my Post Processing GameObject:

enter image description here

unity – UI Element only showing in sceneview and not game in Unity3D

I have a game and in one part, in the start of a scene its supposed to trigger an animation that shows a UI element that covers the whole screen to make a smooth transition from one scene to another.

when i click a button it will trigger a function that triggers an ienumerator (just a function basically) which starts the animation, waits some time, then opens the next scene. the animation it triggers makes the ui show up.

the code:

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

public class levelLoad : MonoBehaviour
{
    public Animator transition;
    public float waitTime = 1f;


    public void transitionLoad(int li)
    {
        Debug.Log("Message through, activating script.");
        StartCoroutine(loadScene(li));
    }

    IEnumerator loadScene(int levelIndex)
    {
        // the set trigger sets the trigger 'starts' which starts the animation that shows the ui element

        transition.SetTrigger("Starts");
        Debug.Log("animations, go");

        yield return new WaitForSeconds(waitTime);

        Debug.Log("Loading Scene");

        // loads scene
        SceneManager.LoadScene(levelIndex);

        Debug.Log("Scene Loaded");
    }
}

so in the animator tab, there is a trigger called “starts” that when triggered, activates crossfade_end which shows the ui element.

crossfade_start hides the ui element.

i get all the debug logs in the code correctly and in game i checked animator, it says that its playing the animations yet in game i dont see the ui element showing up.

anyone has a solution? im using unity 2019.17.4 lts.

also, the ui element is in a different canvas then the main canvas, a canvas that is in the sceneloader gameobject, which has the code above. also that canvas is in layer default, and i checked, default layer is set to showing.

can anyone fix my problem of the ui element showing in scene view but not in game? (this isnt build)

this is an android game.

unity – Procedurally generated mesh makes weird shapes

I’m developping a procedural terrain generator in Unity 2020.3, using Sebastian Lague’s tutorials and knowledge i’ve gathered through college projects.
The heightmap looks just fine, and i had no issues in 2D, but upon generating the Meshes, i’m getting these weird stairs-like shapes:
https://i.imgur.com/Mfg3fM5.png

Debugging that kind of issue has proven quite hard and i spent a few hours not understanding what’s wrong already.
Displaying the values of my heightmap does not show any issue, values are what i would expect from perlin noise.

I need help understanding what’s wrong.

For reference, the noise generation function:

public static float(,) GenerateNoise(int width, int height, int octaves, float persistance, float lacunarity, float scale, Vector2 offset, float redistribution, int seed, 
                                        bool islandMode, float waterCoefficient, float warping1, float warping2
    ) {
        float(,) results = new float(width, height); 
        float begin = Time.realtimeSinceStartup;

        //seed to have the possibility to recreate a noisemap
        System.Random randomGenerator = new System.Random(seed);
        //random offset
        Vector2() octaveOffsets = new Vector2(octaves);
        for(int i = 0; i < octaves; i++)
        {
            float offsetX = randomGenerator.Next(-100000, 100000) + offset.x;
            float offsetY = randomGenerator.Next(-100000, 100000) + offset.y;
            octaveOffsets(i) = new Vector2(offsetX, offsetY);
        }

        for (float y = 0; y < width; y++) {
            for (float x = 0; x < height; x++) {
                // Initial values
                float amplitude = 1;
                float frequency = 1;
                float noiseValue = 0;

                // the FBM algorithm to generate layers
                for (int i = 0; i < octaves; i++) {
                    float xCoord = x / width * scale * frequency + octaveOffsets(i).x;
                    float yCoord = y / height * scale * frequency + octaveOffsets(i).y;

                    //warping reusing code from https://www.iquilezles.org/www/articles/warp/warp.htm
                    //add 1st level of warping
                    Vector2 q = new Vector2(Mathf.PerlinNoise(xCoord, yCoord), 
                                            Mathf.PerlinNoise(xCoord + 5.2f, yCoord + 1.3f));

                    //second level of warping
                    Vector2 r = new Vector2(Mathf.PerlinNoise(xCoord + warping1 * q.x + 1.7f, yCoord + warping1 * q.y + 9.2f), 
                                            Mathf.PerlinNoise(xCoord + warping1 * q.x + 5.2f, yCoord + warping1 * q.y + 1.3f));

                    noiseValue += Mathf.PerlinNoise(xCoord + warping2 * r.x, yCoord + warping2 * r.y) * amplitude;

                    frequency *= lacunarity;
                    amplitude *= persistance;
                }

                //redistribution to allow creation of flat areas if need be
                float finalValue = Mathf.Pow(noiseValue, redistribution);
                //create an island shape by lowering noise value the further you are from the middle of the map
                if (islandMode) 
                    finalValue = finalValue - Vector2.Distance(new Vector2(x, y), new Vector2(width / 2, height / 2)) / (width * waterCoefficient);
                results((int) x, (int) y) = finalValue;
            }
        }

        Debug.Log("time to generate heightmap: " + (Time.realtimeSinceStartup - begin));
        return results;
    }

And the Mesh generation function:

public static Mesh GenerateMesh(float(,) noisemap, float minHeight, float maxHeight, int width, int height, float pointsPerUnit) {
        float begin = Time.realtimeSinceStartup;
        Mesh mesh = new Mesh();
        mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;
        int nx = noisemap.GetLength(1);
        int ny = noisemap.GetLength(0);
       
        Vector3() vertices = new Vector3(nx * ny);
        //calculate vertices
        for (int y = 0; y < ny; y++)
        {
            //only write the point if he is not at the end of a line (as it would not have a point to its right)
            for (int x = 0; x < nx; x++)
            {
                vertices(y * nx + x) = new Vector3((float) x / pointsPerUnit, noisemap(x, y) * maxHeight, (float) y / pointsPerUnit);
            }
        }

        Vector2() uvs = new Vector2(vertices.Length);
        for (int i = 0; i < uvs.Length; i++)
        {
            uvs(i) = new Vector2(vertices(i).x / width, vertices(i).z / height);
        }

        List<int> triangles = new List<int>();
        //skips the first line as it has to points above 
        for (int y = 1; y < ny; y++)
        {
            //only write the point if he is not at the end of a line (as it would not have a point to its right)
            for (int x = 0; x < nx - 1; x++)
            {
                int current = y * nx + x; // the "number" of the current point in a "1D" fashion
                //write current, diagonal, above and current, right, diagonal
                int above = current - ny; //the point above the current
                int rDiagonal = above + 1; //the point in the right diagonal of the current
                int right = current + 1;//the point to the right of the current

                triangles.Add(current);
                triangles.Add(rDiagonal);
                triangles.Add(above);

                triangles.Add(current);
                triangles.Add(right);
                triangles.Add(rDiagonal);
            }
        }

        mesh.SetVertices(vertices);
        mesh.triangles = triangles.ToArray();
        mesh.SetUVs(0, uvs);
        mesh.RecalculateNormals();
        Debug.Log("time to generate mesh: " + (Time.realtimeSinceStartup - begin));
        return mesh;
    }
```