unity – Find out triangles that are not occluded from a camera view?

You could use a rendering pass that writes “triangle IDs” to an offscreen framebuffer instead of rendering colors. Then you can read the pixels from the offscreen framebuffer and get the IDs of all visible triangles. That means you need to extend your vertex data to contain such triangle IDs, create a 32-bit-per-pixel framebuffer, and write a simple fragment shader that only writes the triangle IDs into the framebuffer (and discards color information etc). Depth-testing must of course be enabled.

Note that this solution might miss very small triangles that don’t even occupy a single pixel. It also won’t work properly with triangle strips (you’ll need “3-vertices-per-triangle” vertex buffers instead).

unity – Why the MoveTowards make the transform moving nonstop?

In the Update in the else part, I’m trying to move the transform up from its current position on the exit more up by offset.

When the flag bool exit is true I want the transform to move up more by the offset for example if the offset is 7 then move up on the Y more 7. but it’s moving up non-stop.

I tried to like this with exitPosition variable for storing at exit: but still, it’s moving up non-stop.

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

public class Testing : MonoBehaviour
{
    public float speed;
    public float offset;

    private bool exited = false;
    private Vector3 exitPosition;

    private void Start()
    {
        Debug.Log("Position : " + transform.position);
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.name == "Cube")
        {
            Debug.Log("Exited !");
        }

        exitPosition = new Vector3(transform.position.x,
                transform.position.y + offset, transform.position.z);

        exited = true;
    }

    private void Update()
    {
        if (!exited)
        {
            transform.position += Vector3.up * speed * Time.deltaTime;
        }
        else
        {
            transform.position = Vector3.MoveTowards(transform.position, exitPosition, speed * Time.deltaTime);
        }
    }
}

unet – Unity mirror networking – game laggy for everyone after second client joins

I would like to ask a question about networking (mirror) in unity. I’ve already programed almost a whole game, but I got stuck on unexpected issue. Everything works great (even multiplayer) unless there are more than two players present. At this point the game starts being extremely laggy for everyone. I thought that it was happening due to my poor code optimalisation so I tried to disable all of these “features”. It made absolutely no difference. I tracked down the problem until I disabled almost everything but the core functionality (movement). I’m using Opsive Ultimate character controller (https://assetstore.unity.com/packages/tools/game-toolkits/ufps-ultimate-fps-106748) for movement so finding some “problems” in there is almost impossible! I would love to share the code with you, but since I disabled practically all of it, it does not make much sense at this point. Does anyone have similar experience with mirror networking asset?? (PS my game has quite a big map so I set quality to the lowest possible, which resulted in no success either)

Thanks everyone!

Papouc

c# – Process for Creating Imposters (For Unity)

I’m still working on making a sports stadium with crowd etc. I’ve been reading a lot about ‘Imposters’ and ‘Billboarding’. I want to explore and learn the imposters technique.

But I am stuck at step 1 😐

I have a stadium model made which is empty (no seats or people).

All I want at the moment is seats. I have the model made in Maya for a seat.

  1. Do I need to make (and import to Unity) both a low-poly and high-poly version of the model.
  2. How exactly is an ‘imposter’ asset stored in data (specifically if used in Unity)?
  3. Do I need to make 2d images/textures of many angles of the seat?

I do have more questions, but these may be enough to get me started.

Thanks as always for any help.

unity – Help me i don’t know where is the problem

it pops up when I start walking my figure.

IndexOutOfRangeException: Index was outside the bounds of the array.
UnityStandardAssets.Characters.FirstPerson.FirstPersonController.PlayFootStepAudio () (at Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/FirstPersonController.cs:173)
UnityStandardAssets.Characters.FirstPerson.FirstPersonController.ProgressStepCycle (System.Single speed) (at Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/FirstPersonController.cs:160)
UnityStandardAssets.Characters.FirstPerson.FirstPersonController.FixedUpdate () (at Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/FirstPersonController.cs:131

using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using UnityStandardAssets.Utility;
using Random = UnityEngine.Random;

#pragma warning disable 618, 649
namespace UnityStandardAssets.Characters.FirstPerson
{
    (RequireComponent(typeof (CharacterController)))
    (RequireComponent(typeof (AudioSource)))
    public class FirstPersonController : MonoBehaviour
    {
        (SerializeField) private bool m_IsWalking;
        (SerializeField) private float m_WalkSpeed;
        (SerializeField) private float m_RunSpeed;
        (SerializeField) (Range(0f, 1f)) private float m_RunstepLenghten;
        (SerializeField) private float m_JumpSpeed;
        (SerializeField) private float m_StickToGroundForce;
        (SerializeField) private float m_GravityMultiplier;
        (SerializeField) private MouseLook m_MouseLook;
        (SerializeField) private bool m_UseFovKick;
        (SerializeField) private FOVKick m_FovKick = new FOVKick();
        (SerializeField) private bool m_UseHeadBob;
        (SerializeField) private CurveControlledBob m_HeadBob = new CurveControlledBob();
        (SerializeField) private LerpControlledBob m_JumpBob = new LerpControlledBob();
        (SerializeField) private float m_StepInterval;
        (SerializeField) private AudioClip() m_FootstepSounds;    // an array of footstep sounds that will be randomly selected from.
        (SerializeField) private AudioClip m_JumpSound;           // the sound played when character leaves the ground.
        (SerializeField) private AudioClip m_LandSound;           // the sound played when character touches back on ground.

        private Camera m_Camera;
        private bool m_Jump;
        private float m_YRotation;
        private Vector2 m_Input;
        private Vector3 m_MoveDir = Vector3.zero;
        private CharacterController m_CharacterController;
        private CollisionFlags m_CollisionFlags;
        private bool m_PreviouslyGrounded;
        private Vector3 m_OriginalCameraPosition;
        private float m_StepCycle;
        private float m_NextStep;
        private bool m_Jumping;
        private AudioSource m_AudioSource;

        // Use this for initialization
        private void Start()
        {
            m_CharacterController = GetComponent<CharacterController>();
            m_Camera = Camera.main;
            m_OriginalCameraPosition = m_Camera.transform.localPosition;
            m_FovKick.Setup(m_Camera);
            m_HeadBob.Setup(m_Camera, m_StepInterval);
            m_StepCycle = 0f;
            m_NextStep = m_StepCycle/2f;
            m_Jumping = false;
            m_AudioSource = GetComponent<AudioSource>();
            m_MouseLook.Init(transform , m_Camera.transform);
        }


        // Update is called once per frame
        private void Update()
        {
            RotateView();
            // the jump state needs to read here to make sure it is not missed
            if (!m_Jump)
            {
                m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
            }

            if (!m_PreviouslyGrounded && m_CharacterController.isGrounded)
            {
                StartCoroutine(m_JumpBob.DoBobCycle());
                PlayLandingSound();
                m_MoveDir.y = 0f;
                m_Jumping = false;
            }
            if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded)
            {
                m_MoveDir.y = 0f;
            }

            m_PreviouslyGrounded = m_CharacterController.isGrounded;
        }


        private void PlayLandingSound()
        {
            m_AudioSource.clip = m_LandSound;
            m_AudioSource.Play();
            m_NextStep = m_StepCycle + .5f;
        }


        private void FixedUpdate()
        {
            float speed;
            GetInput(out speed);
            // always move along the camera forward as it is the direction that it being aimed at
            Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x;

            // get a normal for the surface that is being touched to move along it
            RaycastHit hitInfo;
            Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo,
                               m_CharacterController.height/2f, Physics.AllLayers, QueryTriggerInteraction.Ignore);
            desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized;

            m_MoveDir.x = desiredMove.x*speed;
            m_MoveDir.z = desiredMove.z*speed;


            if (m_CharacterController.isGrounded)
            {
                m_MoveDir.y = -m_StickToGroundForce;

                if (m_Jump)
                {
                    m_MoveDir.y = m_JumpSpeed;
                    PlayJumpSound();
                    m_Jump = false;
                    m_Jumping = true;
                }
            }
            else
            {
                m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime;
            }
            m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime);

            ProgressStepCycle(speed);
            UpdateCameraPosition(speed);

            m_MouseLook.UpdateCursorLock();
        }


        private void PlayJumpSound()
        {
            m_AudioSource.clip = m_JumpSound;
            m_AudioSource.Play();
        }


        private void ProgressStepCycle(float speed)
        {
            if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0))
            {
                m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))*
                             Time.fixedDeltaTime;
            }

            if (!(m_StepCycle > m_NextStep))
            {
                return;
            }

            m_NextStep = m_StepCycle + m_StepInterval;

            PlayFootStepAudio();
        }


        private void PlayFootStepAudio()
        {
            if (!m_CharacterController.isGrounded)
            {
                return;
            }
            // pick & play a random footstep sound from the array,
            // excluding sound at index 0
            int n = Random.Range(1, m_FootstepSounds.Length);
            m_AudioSource.clip = m_FootstepSounds(n);
            m_AudioSource.PlayOneShot(m_AudioSource.clip);
            // move picked sound to index 0 so it's not picked next time
            m_FootstepSounds(n) = m_FootstepSounds(0);
            m_FootstepSounds(0) = m_AudioSource.clip;
        }


        private void UpdateCameraPosition(float speed)
        {
            Vector3 newCameraPosition;
            if (!m_UseHeadBob)
            {
                return;
            }
            if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded)
            {
                m_Camera.transform.localPosition =
                    m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude +
                                      (speed*(m_IsWalking ? 1f : m_RunstepLenghten)));
                newCameraPosition = m_Camera.transform.localPosition;
                newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset();
            }
            else
            {
                newCameraPosition = m_Camera.transform.localPosition;
                newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset();
            }
            m_Camera.transform.localPosition = newCameraPosition;
        }


        private void GetInput(out float speed)
        {
            // Read input
            float horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
            float vertical = CrossPlatformInputManager.GetAxis("Vertical");

            bool waswalking = m_IsWalking;

#if !MOBILE_INPUT
            // On standalone builds, walk/run speed is modified by a key press.
            // keep track of whether or not the character is walking or running
            m_IsWalking = !Input.GetKey(KeyCode.LeftShift);
#endif
            // set the desired speed to be walking or running
            speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed;
            m_Input = new Vector2(horizontal, vertical);

            // normalize input if it exceeds 1 in combined length:
            if (m_Input.sqrMagnitude > 1)
            {
                m_Input.Normalize();
            }

            // handle speed change to give an fov kick
            // only if the player is going to a run, is running and the fovkick is to be used
            if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0)
            {
                StopAllCoroutines();
                StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown());
            }
        }


        private void RotateView()
        {
            m_MouseLook.LookRotation (transform, m_Camera.transform);
        }


        private void OnControllerColliderHit(ControllerColliderHit hit)
        {
            Rigidbody body = hit.collider.attachedRigidbody;
            //dont move the rigidbody if the character is on top of it
            if (m_CollisionFlags == CollisionFlags.Below)
            {
                return;
            }

            if (body == null || body.isKinematic)
            {
                return;
            }
            body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse);
        }
    }
}
```

unity – Creating a Full Stadium of People, Ready as a Game Asset (ie. not too CPU intensive)

In answer to one of your comments:

I actually have the same question, but regarding the seats in the stadium. Would it be better to make them in maya (all of them) or is it better to import just one chair mesh to Unity and place them procedurally?

There is extra performance overhead for multiple GameObjects; for example, it’s faster to render one mesh containing 100 chairs than to render a single chair mesh 100 times. You can reduce overhead by doing manual instanced rendering using Graphics.DrawMeshInstanced() but that is done with code and can be an extra headache to set up. I’d suggest grouping multiple chairs into one mesh.

However, you should not put all of the chairs in the entire arena into a single mesh, as this prevents frustum culling from working. Frustum culling refers to skipping render of objects that are not inside the camera’s boundaries. If all of the chairs are in a single mesh that wraps all the way around the arena, that means that at least some of the chairs will be visible to the camera no matter what direction the camera is pointed, preventing frustum culling. I once worked on a racing game for mobile where the artist had made the barrier around the entire track as a single 200k poly mesh. This ended up causing major performance issues because the engine could never cull any part of the barrier, so we eventually had to break the barrier into segments.

I would suggest grouping chairs into sections, and making each section a single mesh. This way you have less overhead than if each chair was its own object, but frustum culling will still work for sections of chairs that are not in front of the camera.

EDIT: As DMGregory noted in a comment, in the likely event that the chairs are completely stationary, you can also use static batching to have Unity automatically combine multiple instances of a mesh into a single mesh. So for example, if you imported a mesh containing 1 chair and added 500 copies of that chair to the scene, using static batching you could let Unity combine multiple chairs into a single mesh. I do not know offhand how this would work with frustum culling.

unity – The name ‘txt’ does not exist in the current context

unity – The name ‘txt’ does not exist in the current context – Game Development Stack Exchange

unity – Sort Textures by name before looping through them

im using a system to get textures from the device persistent data path and assign them to an array in order to show them in the game scene. So far everything works as expected, images are getting pulled into the array and are selected based on the level index. My issue is that on some android devices each time the image is loaded its either random or its a different image than it should be.

  public void LoadTextureArray(string _dirname)
    {

        var fileNames = Directory.GetFiles(Application.persistentDataPath + "/" + _dirname + "/", "*.jpg");

        source = new Texture2D(fileNames.Length);
        
        int index = 0;
        foreach (var fileName in fileNames)
        {
            source(index) = LoadTextureFromPath(fileName);
            source(index).name = fileName;
            index++;
        }
    }

    public Texture2D LoadTextureFromPath(string path)
    {
        if (string.IsNullOrEmpty(path))
        {
            Debug.LogError("Texture path is null or empty");
            return null;
        }

        if (!File.Exists(path))
        {
            Debug.LogError($"File not found: {path}");
            return null;
        }

        byte() bytes = File.ReadAllBytes(path);
        Texture2D texture = new Texture2D(2048, 2048, TextureFormat.RGB24, false);
        texture.LoadImage(bytes);
        Debug.Log("success");
        return texture;
    }

and i assign them based on another variable with this code here

 if (LevelSystemManager.Instance.CurrentLevel < source.Length)
                    {
                        selectedText = source(LevelSystemManager.Instance.CurrentLevel);
                        DifficultySet();
                        Debug.Log("selected Texture Name is :" + selectedText.name);
                    }

The LoadTextureArray function is called on Awake and on Start i do the assignment based on that index. Now in both Unity editor and my phone everything works fine and no matter how many times i load the level its the same image. Whereas on my wifes it either skips a couple of images from the array (displaying the 5th for instance as index 1) or everytime i open the level i see a different one!

Thank you!

Edit : it seems my problem is that i need to sort them out before assigning them to that array so any help would be appreciated!

unity – Error “Non-invocable member “CharacterController” cannot be used like a method” when directly following tutorial

I assume you can tell from the issue I’m having that I’m not very good at this. The issue is that I’m directly following this tutorial on YouTube, practically click for click, but am getting an error that is not on the video. Here is my code:

using System.Collections;

using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{

public float moveSpeed;
public float jumpForce;
public bool isGrounded;
public CharacterController controlo;
public Vector3 moveDirection;
void Start()
{
    controlo = GetComponent < CharacterController() >;
}

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

    moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));

    if (Input.GetButtonDown("Jump"))
    {
        moveDirection.y = jumpForce;
    }

    controlo.Move(moveDirection * Time.deltaTime);

}}

Upon running this, I get the error “Non-invocable member “CharacterController” cannot be used like a method”. How do I solve this?

unity – How can I record and replay axis input accurately for testing?

I want to do integration testing for an old C#/Unity project. The project uses its own input system, so I can’t use inputEventTrace or any other convenient Unity class. So I subscribed a new game object to the custom input system so that it records any input detected in each frame.

But when I replay, because of the difference in frame times, the replays are not quite equal to the original playthrough (especially because of the axis input). My understanding is that input in Unity is not event-based, so I can’t think of any way to perfectly mimic the input given different frame times. Does anyone know of a way to do this?

DreamProxies - Cheapest USA Elite Private Proxies 100 Private Proxies 200 Private Proxies 400 Private Proxies 1000 Private Proxies 2000 Private Proxies ExtraProxies.com - Buy Cheap Private Proxies Buy 50 Private Proxies Buy 100 Private Proxies Buy 200 Private Proxies Buy 500 Private Proxies Buy 1000 Private Proxies Buy 2000 Private Proxies ProxiesLive Proxies-free.com New Proxy Lists Every Day Proxies123