#archived-code-general

1 messages · Page 293 of 1

sterile sorrel
#

foreach (GameObject position in rampEMPTY)
{
if (Vector3.Distance(position.transform.position, transform.position) <= chunkLength)
{
Instantiate(ramp, position.transform);
}
}

#

ive been trying to think of the right way to do these things, and i finally did it 😄

runic nimbus
#

Bump on this question

#

                Vector3 handsDirection = hand2.position - hand1.position;
                transform.rotation = Quaternion.LookRotation(handsDirection );```
#

See how it flips around after going above 90 degrees?

#

I know jack about quaternions so I dont know how to work with this

lunar python
#

how to you apply changes from Input to Finite State Machine. Do you have to check whether a state can perform some capabilities before executing it. Like when player is swimming, they can't jump

runic nimbus
spring creek
runic nimbus
#
if(CharacterState == State.Standing) {
  if(Input.PressedC) { CharacterState = State.Crouching; }
  if(Input.HoldingShift) { CharacterState = State.Running; }
}
else if(CharacterState == State.Crouching) {
  if(Input.PressedC) { CharacterState = State.Standing; }
}
else if(CharacterState == State.Proning) {
  if(Input.PressedC) { CharacterState = State.Crouching; }
}```
@lunar python An example of a state machine that uses input to handle a character's pose
lunar python
#

what if I want the player to do both jumping and moving at the same time?

spring creek
runic nimbus
#

Oh yes my bad

spring creek
#

Eh, it's just an example. All good 😸

#

It gets the point accross

lunar python
#

platformer usually allow player to do a bit of air hovering while at the peak of jump

runic nimbus
# lunar python what if I want the player to do both jumping and moving at the same time?

Well you could do something like this

if(CharacterState == State.Standing) {
  if(Input.PressedC) { CharacterState = State.Crouching; }
  if(Input.HoldingShift) { CharacterState = State.Running; }
  if(Input.PressedSpace) { Jump(); }
}
else if(CharacterState == State.Crouching) {
  if(Input.PressedC) { CharacterState = State.Standing; }
}
else if(CharacterState == State.Proning) {
  if(Input.PressedC) { CharacterState = State.Crouching; }
}```
#

Jumping isn't exactly a state, and can be separate

#

But this way, you could only jump when standing

lunar python
#

what if I do something like this

#

should this be possible?

runic nimbus
#

Gives player the ability to do certain actions, cool

lunar python
#

I seperate states by Unique conditions that allows player to do certain actions

high summit
#

Trying to add doors to my dungeon generator but for some reason the script I made is doing literally nothing. ```cs
public class DoorSpawner : MonoBehaviour
{
[SerializeField] private GameObject doorPrefab;

private void OnTriggerEnter(Collider other)
{
    // Check if the colliding object is another DoorPoint
    if (other.CompareTag("Door"))
    {
        // Destroy the colliding DoorPoint and its associated doorFiller objects
        Destroy(other.gameObject);
        Destroy(other.transform.parent.gameObject);

        // Instantiate a new Door prefab at the position of this DoorPoint
        InstantiateDoor();
    }
}

private void InstantiateDoor()
{
    // Instantiate the Door prefab at the position and rotation of this DoorPoint
    GameObject door = Instantiate(doorPrefab, transform.position, transform.rotation);
}

}``` I'm trying to make it such that when two doorpoints are colliding (Meaning that two rooms with doors at that spot are adjacent), they will each be destroyed along with the wall filler and replaced with a door. At the moment nothing happens when they collide and I am not sure why

#

Attached a couple pictures showing how the doorPoint is setup, and what one and the filler look like in the scene

#

In the hierarchy doorPoints are children of the fillers

latent latch
#

do you have the requirements to make OnTriggerEnter to work

high summit
latent latch
#

You're missing one component there for it

high summit
#

Wait what am I missing

latent latch
#

you need at least one thing to have a rigidbody

#

can be kinematic

high summit
#

ah

#

let me try that rq thanks

latent latch
#

otherwise, you can just do like a overlapbox operation

high summit
#

figured rigid body was for physics and stuff

#

part of me thinks I should've chosen an easier first project but part of me is really having fun with the complexity

latent latch
#

collider is part of physics too, but yeah I don't know why the trigger method has to be so connected to it

high summit
#

something like this is fine tho?

latent latch
#

ye

#

could always remove them later too

high summit
#

alright nice, sort of works

#

just gotta make it only instantiate one door somehow

#

and also fix the prefabs that have the doorpoint slightly too low

lean sail
#

I realized a flaw with my scriptable object game effects which are "when X happens do Y". I wanted to make a feature, every few seconds heal some amount. Since im using SO, i realized there is only one instance so every character with this effect will add to the counter. Then one character ends up consuming the health and the timer resets.
I need unique instances and know I can Instantiate(SO) or CreateInstance but is there a reason to use one or the other? I assume Instantiate is the same but it copies the data from my existing SO which I want.
Also are there any downsides to use Instantiate here? It seems to work so far but I am just curious if there is something else I need to do. Like do I have to destroy the objects after?

latent latch
#

Instantiate usually copies anything serialized usually (much like prefabs) while CreateInstance is like making a new SO instance in the editor as it'll always have defaults

#

defaults from the original SO instance

#

dont quote me on this ;)

#

I did actually make a effect system using SOs only but I ditched that idea for just plain ol' c# classes

high summit
#

Issue is that both doorpoints register the collision and go through their process, which involves spawning the door

#

so two get spawned

lean sail
latent latch
#
public class DoorSpawner : MonoBehaviour
{
    public bool QueuedForDestruction = false;
    private void OnTriggerEnter(Collider other)
    {
        if(QueuedForDestruction) return;

        if(other.TryGetComponent(out DoorSpawner door))
        {
          Destroy(door.gameObject);
          door.QueuedForDestructon = true;
        }
    }
}```
latent latch
#

or some similar idea

high summit
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DoorSpawner : MonoBehaviour
{
    [SerializeField] private GameObject doorPrefab;
    private bool doorBeingSpawned = false;

    private void OnTriggerEnter(Collider other)
    {
        // Check if a door is not already being spawned and the colliding object is another DoorPoint
        if (!doorBeingSpawned && other.CompareTag("Door"))
        {
            // Set the flag to indicate that a door is being spawned
            doorBeingSpawned = true;

            // Destroy the colliding DoorPoint and its associated doorFiller objects
            Destroy(other.gameObject);
            Destroy(transform.parent.gameObject);

            // Instantiate a new Door prefab at the position and rotation of this DoorPoint
            InstantiateDoor();
        }
    }

    private void InstantiateDoor()
    {
        // Instantiate the Door prefab at the position and rotation of this DoorPoint
        GameObject door = Instantiate(doorPrefab, transform.position, transform.rotation);

        // Reset the flag to allow for the next door to spawn
        doorBeingSpawned = false;
    }
}``` this is what I currently have but spawns two doors anyways
latent latch
#

so it's not the door checking OnTrigger but this DoorSpawner?

#

there's no race conditions that I'm aware of

high summit
#

All rooms have doorfillers and those fillers have doorpoints as children. If two overlap, that means a door should go there, so all of those should be destroyed and a single door spawned

#

I have a dumb idea for a solution

#

have each generate a random number when they collide and the lower number gets destroyed

#

rock paper scissors for life

latent latch
#

im not too sure, but something to run step by step in the debugger if needed

high summit
#

Ugh I've been trying to use a coroutine or invoke to add a delay in order to spawn one door but the coroutine return makes the following line unreachable, and the invoke just doesn't work and idk why. ```cs
private void OnTriggerEnter(Collider other)
{
if (!doorBeingSpawned && other.CompareTag("Door"))
{
doorBeingSpawned = true;
Destroy(other.gameObject);
Destroy(transform.parent.gameObject);
Debug.Log("Invoking InstantiateDoor");
Invoke("InstantiateDoor", 0.1f);
}
}

private void InstantiateDoor()
{
    Debug.Log("Instantiating door...");
    // Instantiate the Door prefab at the position and rotation of this DoorPoint
    GameObject door = Instantiate(doorPrefab, transform.position, transform.rotation);
    // Reset the flag to allow for the next door to spawn
    doorBeingSpawned = false;
}```
#

In this code the first debug prints but the secont debug never does

#

Tried with coroutines earlier but those didn't work either and idk why

rigid island
high summit
#

thats one of the steps that has to happen yeah

rigid island
#

can't invoke if its destroying

high summit
#

should I change the order

#

Just tested with the parent destruction happening second to last but still doesnt work

west lotus
#

You cant run a coroutine on a Monobehaviour that is gonna get destroyed next frame and expect it to wait for 0.1s or what ever

high summit
high summit
rigid island
#

why do you need delay

#

You could also make the whole TriggerEnter a coroutine

high summit
latent latch
#

there doesnt need to be delay

west lotus
latent latch
#

there's no race conditions

rigid island
#

delay might be hiding a bigger issue

high summit
high summit
#

so when a collision happens rn it leads to double trigger

rigid island
latent latch
#

for the most part, Unity is single threaded (as far as user-space callbacks go) , if it happens on a single frame then it's probably executing in some order

latent latch
#

oh that's a pretty good idea

high summit
#

And it worked

#

tyvm

high crow
#

Hello i just have a question about unity netcode im trying to add a force to an object with a severrpc as the client has no rights. but it just isnt the player is being referenced properly and the m value is correct and changing with the rest of my code if anyone has any tips please help. btw the function is being called in update.
public void movementServerRpc(Vector2 m,ServerRpcParams serverRpcParams = default){
var clientId = serverRpcParams.Receive.SenderClientId;
if (NetworkManager.ConnectedClients.ContainsKey(clientId)){
var client = NetworkManager.ConnectedClients[clientId];

        client.PlayerObject.GetComponent<Rigidbody2D>().AddForce(m,ForceMode2D.Force);
    }
}
#

extra info:
i have got a network trasform on the object and it is not updating the postion in the sever
its not just the add force trying to change the trasform also does nothing although it is being called as the debug.log is working

limber wharf
#

hey guys, so I want to directly download from OneDrive using this method:
https://api.onedrive.com/v1.0/shares/u!XXXXX/root/content
where XXXXX is the base 64 equivalent of the url
however when I convert the url to Base64URL format and try to open the final url, it responds with:
{"error":{"code":"unauthenticated","message":"The caller is not authenticated."}}

Any idea how to fix this?

quartz folio
limber wharf
#

how can I do that?

limber wharf
#

isn't there some simpler way of downloading directly from onedrive? or maybe use different storage?

high crow
#

ok an update on the problem it is infact increaceing the veloctiy but not changeing the position which i didnt think was possible

limber wharf
high crow
limber wharf
lean sail
# high crow ok an update on the problem it is infact increaceing the veloctiy but not change...

#archived-networking but you probably shouldnt be doing multiplayer if you arent really confident in coding/debugging. what you are doing in the server rpc doesnt really make sense, this script can just have direct access to the rb. The same way it does in single player. Then you can just add force in like fixedupdate based on a network variable (for the vector2)
If a person does not own the object, it will not move the object no matter what you assign to the velocity.

lean sail
high crow
lean sail
high crow
#

thats all good thats for the tips anyway

frigid sequoia
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class InteractionManager : MonoBehaviour
{
    public Text valueText;
    int progress = 0;
    public Slider slider;

    void OnEnable()
    {
        PlayerInteractor.OnInteract += HandleInteractEvent;
    }

    void OnDisable()
    {
        PlayerInteractor.OnInteract -= HandleInteractEvent;
    }

    void HandleInteractEvent()
    {
        UpdateProgress();
        
    }

    public void UpdateProgress()
    {
        progress++;
        slider.value = progress;
        StartCoroutine(ResetSliderAfterDelay(2f));
    }

    private IEnumerator ResetSliderAfterDelay(float delay)
    {
        yield return new WaitForSeconds(delay);

        // Reset progress and slider value after the delay
        progress = 0;
        slider.value = 0;
    }
}

I am trying to make a slider that interacts with my interaction system and it works but I can´t get it to reset the slider

frigid sequoia
#

sorry but noone was helping

knotty sun
#

not the point

terse aurora
#

that's the script of my camera, but if I use collision.gameObject.CompareTag("change1") it will detect camera's collisons, how to get the collisions of my Player?

#

because like this it doesn't work

quartz folio
terse aurora
#

like this

swift falcon
#
    {
        if (Input.GetMouseButtonDown(1))
        {
            Vector2 MousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            Vector3 direction = MousePosition - (Vector2)transform.position;
            float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
            Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward);

            _rigidbody.MoveRotation(Quaternion.RotateTowards(transform.rotation, rotation, _rotationSpeed * Time.deltaTime));
        }
    }

I may be stupid. but for some reason this is not working. it gives me this error.

Player.RotateTowardsCursor () (at Assets/Scripts/Player/PlayerMovement.cs:58)
Player.FixedUpdate () (at Assets/Scripts/Player/PlayerMovement.cs:29)
hard viper
#

the line with an NRE contains the variable that is the problem

void turtle
#

Why is everyone using public variables for ScriptableObjects? Like this looks like a big sin for me.

hard viper
#

in this case, line 58

swift falcon
#

I checked and nothing is there

#

line 58 is: Vector2 MousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);

hard viper
swift falcon
#

it was working before and now it is not so idk

void turtle
# hard viper it is 🙃

yeah the { get; } getter is not working and the only option seems to be setting up manual getters?

hard viper
#

it needs a private setter to actually define the backing field and connect to unity

void turtle
#

okay thanks

warm kraken
#

hey guys. there's a lack of collider primitives in unity. is there a good asset with primitive colliders? what would you recommend?

heady iris
#

3D collider primitives are provided by PhysX.

#

so you aren't going to be adding your own primitives

knotty sun
warm kraken
#

cylinder cone donut etc

#

usual stuff

knotty sun
#

make em in blender then use a Mesh collider

warm kraken
#

what if i want to change cylinder collider's shape size and offset like im able to do with default colliders in unity?

rigid island
#

cant

warm kraken
#

yep. thats why i asked if you guys know the best pack for it. i searched and there are several. im trying to get a primitive collider pack where you have flexibility with size and shape

knotty sun
warm kraken
#

so my custom blender colliders will be more optimized than default ones in unity?

#

ok then

rigid island
#

mesh colliders are expensive, tread carefully. The basic ones unity has are always more performant

heady iris
#

Primitive colliders are shapes that are easy for PhysX to reason about.

#

I imagine they were chosen for a reason.

#

Toruses, notably, are not convex.

#

Cylinders are harder to reason about than capsules.

static matrix
#

I seem to be getting a lot of perf hog on Physics2D.FindNewContacts any idea what might be causing this?

#

AHAAAAAAAAAAAAAAAAAAAAAAAAAA
I'VE FIGURED OUT THE BUG
when the linerenderer is turned off, it counts as the renderer turning off, triggering "OnBecameInvisible" and starting the countdown for the offscreen kill

#

so I just need to tell it to reset the offscreen-ness when the linerenderer goes away

polar wadi
#

Hey. I would like to hide the objects between camera and player. How is it called and how could I do this best? I tried with ray cast but that only works semi good

rigid island
#

it will proably be easier with some sort of cutout shader though

polar wadi
#

I tried it with a shader. But with that the walls are cutout strangely

rigid island
#

idk what strangely means

polar wadi
#

one moment

#

well

#

for some reason now it works as expected

#

XD

#

before in play mode it was messed up

#

i saw like two cutout cirlces

#

an inner and outer and between them the wall was there

rigid island
#

could be it needed playmode to work properly

polar wadi
#

it was in play mode XD

rigid island
#

the preview sometimes may not do justice

#

oh weird

polar wadi
#

now i can reproduce it

#

It was due diffrent cutouts in materials

rigid island
polar wadi
#

No I had two materials with diffrent cutout size. so it somehow messed it up in render

rigid island
#

ahh gotcha

polar wadi
#

but anyway. thanks for resonding 🙂

main pawn
#

Hey, I've noticed some weird behaviour with AudioSource.isPlaying. Basically, I'm using it to play random sounds from a set one after another. It will play the first sound, then check isPlaying until it can play the next ones. But it never gets to the next one.

#

Even if the source is totally silent

#

Any ideas?

rigid island
swift falcon
#

Alright, this is my current code:

    private void Awake()
    {
        _rigidbody = GetComponent<Rigidbody2D>();
    }

    private void FixedUpdate()
    {
        SetPlayerVelocity();
        RotateInDirectionOfInput();
        RotateTowardsCursor();
    }

    private void SetPlayerVelocity()
    {
        _smoothedMovementInput = Vector2.SmoothDamp(
            _smoothedMovementInput,
            _movementInput,
            ref _movementInputSmoothVelocity,
            _time);

        _rigidbody.velocity = _smoothedMovementInput * _speed;
    }

    private void RotateInDirectionOfInput()
    {
        if (_movementInput != Vector2.zero)
        {
            Quaternion targetRotation = Quaternion.LookRotation(transform.forward, _smoothedMovementInput);
            Quaternion rotation = Quaternion.RotateTowards  (transform.rotation, targetRotation, _rotationSpeed * Time.deltaTime);

            _rigidbody.MoveRotation(rotation);
        }
    }

    private void RotateTowardsCursor()
    {
        if (Input.GetMouseButton(1))
        {
            Vector2 screenPosition = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
            Vector3 worldPosition = Camera.main.ScreenToWorldPoint(screenPosition);
            Vector2 playerPosition = new Vector2(transform.position.x, transform.position.y);
            Vector2 direction = ((Vector2) worldPosition - playerPosition).normalized;
            float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;

            Quaternion rotationmouse = Quaternion.AngleAxis(angle - 90, Vector3.forward);

            _rigidbody.MoveRotation(Quaternion.RotateTowards(transform.rotation, rotationmouse, _rotationSpeed * Time.deltaTime));
        }
    }






    private void OnMove(InputValue inputValue)
    {
        _movementInput = inputValue.Get<Vector2>();
    }
}

Whenever my character touches another object (especially a corner of an object) it starts randomly spinning

rigid island
#

lock rigidbody rotation on Z

swift falcon
#

that locks all my rotation haha as my code rotates the rigidbody

rigid island
#

nvm

swift falcon
#

nope

#

oh alright

crude mortar
#

if your character is a circle anyways than you don't really need to rotate it with physics

#

if you do want to use physics, you could just override the rigidbody angular rotation at all times

swift falcon
#

how would i make it so it rotates without physics?

rigid island
#

could've sworne MoveRotation would still work with locked Z

crude mortar
#

lock the rotation like what was recommended earlier, then just manually rotate the rigidbody

crude mortar
rigid island
#

nah they have that already thats why i was confused

crude mortar
#

oh, I didn't read the code up there

swift falcon
#

got it

#

set rotation moves when its locked

#

move rotation doesnt

#

but the problem is

#

that removes my dampening

rigid island
#

yea ig because MoveRotation still uses physics

crude mortar
#

doesn't seem like it should remove your dampening.. or at least I wouldn't expect it to. should be same rotation getting calculated, just applied differently

swift falcon
#

how would one fix it?

crude mortar
#

well, explain what you mean by dampening exactly

#

if you mean the rotation is instant now for some reason, maybe you accidentally got rid of your RotateTowards.. ?

swift falcon
#

nope

#

it is instant

#

but i did not remove

#

the rotatetowards

#

i think its because rotatetowards uses physics (maybe?)

crude mortar
#

no (it doesnt use physics)

#

can you show code that actually compiled?

swift falcon
#
    private void Awake()
    {
        _rigidbody = GetComponent<Rigidbody2D>();
    }

    private void FixedUpdate()
    {
        SetPlayerVelocity();
        RotateInDirectionOfInput();
        RotateTowardsCursor();
    }

    private void SetPlayerVelocity()
    {
        _smoothedMovementInput = Vector2.SmoothDamp(
            _smoothedMovementInput,
            _movementInput,
            ref _movementInputSmoothVelocity,
            _time);

        _rigidbody.velocity = _smoothedMovementInput * _speed;
    }

    private void RotateInDirectionOfInput()
    {
        if (_movementInput != Vector2.zero)
        {
            Quaternion targetRotation = Quaternion.LookRotation(transform.forward, _smoothedMovementInput);
            Quaternion rotation = Quaternion.RotateTowards  (transform.rotation, targetRotation, _rotationSpeed * Time.deltaTime);

            _rigidbody.SetRotation(rotation);
        }
    }

    private void RotateTowardsCursor()
    {
        if (Input.GetMouseButton(1))
        {
            Vector2 screenPosition = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
            Vector3 worldPosition = Camera.main.ScreenToWorldPoint(screenPosition);
            Vector2 playerPosition = new Vector2(transform.position.x, transform.position.y);
            Vector2 direction = ((Vector2) worldPosition - playerPosition).normalized;
            float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;

            Quaternion rotationmouse = Quaternion.AngleAxis(angle - 90, Vector3.forward);

            _rigidbody.SetRotation(Quaternion.RotateTowards(transform.rotation, rotationmouse, _rotationSpeed * Time.deltaTime));
        }
    }






    private void OnMove(InputValue inputValue)
    {
        _movementInput = inputValue.Get<Vector2>();
    }
}
crude mortar
#

what if you just do transform.rotation = rotation for them instead, and also double check your rotation speed (although I doubt thats the issue)

swift falcon
#

uh no

#

that fucked everything up

#

ill send a vid

crude mortar
#

well yeah.. your camera is a child of your player (it will inherit rotations)

#

how was it not doing that behavior before?

swift falcon
#

tbh idk, my camera doesnt get affected by my player's rigidbody rotation or position

crude mortar
swift falcon
#

i know

#

also this fucks it up as now if i hold right click (which changes the rotation to where my mouse is) while moving it bugs out

#

which it wasnt doing with the physics

crude mortar
#

probably mostly luck that it was working before, your logic is incomplete. You should only rotate towards one or the other (either movement direction or mouse direction)

#

right now it tries to rotate towards both when you hold the mouse button

swift falcon
#

no it was actually good the way it was

#

lemme switch back and show you

crude mortar
#

no

swift falcon
#

alright

crude mortar
#

I am saying that it was just luck that it appeared to look good, it was still actually trying to rotate to 2 different directions at the same time

#

the delay of the interpolation physics must have made it unnoticeable

#

you should wrap your "RotateInDirectionOfInput" code in a if (!Input.GetMouseButton(1))

swift falcon
#

yeah thats what i was about to do

#

ty

#

I actually don't know how but now the dampening works with
_rigidbody.SetRotation(rotation); so 🤷‍♂️

#

thank you anyways <3

crude mortar
#

glad it works

merry sierra
rigid island
merry sierra
#

by pivots u mean firepoints?

rigid island
#

and bullet

merry sierra
#

nah they are placed correctly when i am not moving it works perfectly fine but when i move things get messy

rigid island
merry sierra
#

local pivot

rigid island
merry sierra
#

yeah same thing

rigid island
#

it looks like the bullet is shooting fine is just the trail lagging

merry sierra
#

yeah trail is child of bullet

rigid island
#

yeah I think thats whats causing that "look" but the bullet is shooting fine

#

try speed up duration time you will seee it will prob be better

heady iris
#

the trails last too long, yes

merry sierra
#

yeah its better but theres still a delay

rigid island
#

they're weirdly rotating

merry sierra
#

i think that is because the car is rotatating and they always go forwards so its an illusion i guess

rigid island
#

when i need to debug something fast i have mapped keys for Time.timeScale = 0.05f or something

rigid island
#

you try increase the bullet speed?

merry sierra
#

yea i already doubled it

rigid island
#

you're passing the rotation of now not the one you're going to be in. by the time it happens the car already rotated , I think..

#

never tried shooting rigidbodies on moving objects like this, i typically go for raycasts on that. So I'm not sure

merry sierra
#

with raycast cant show that a turret is shooting

rigid island
#

sure you can

merry sierra
#

but i have to move the bullet manually and it will also lag i guess

#

like from starting point to the end point

rigid island
#

you can simulate it faster than a physics object can accelerate in physics loop

merry sierra
#

or to just add muzzle flash and hit effect to fake it?

rigid island
#

like the lines right?

merry sierra
#

yeah lines

merry sierra
rigid island
#

you can make instant ones too or give them a slight delay , but never tried on rotating object that adds extra challange

rigid island
#

ideally cause Update will run more frequent should be able to move it faster than a rigidbody can accelerate (accounting for mass ig)

merry sierra
#

hmm will try with raycast which ever feels better will use it

rigid island
#

worth a shot

#

ForceMode.Impulse is taking mass into account another thing to consider

lunar python
#

is it only me whos not seeing a problem with the bullets

rigid island
#

bullet is spawning behind the firepoint

#

also you're def passing the wrong rotation or the pivot you showed me was in global mode @merry sierra

#

physics... a double edge sword

merry sierra
#

yeah that i was trying something now i put bullet firepoint bit more forward

#

it looks much better and with muzzle flash it will look better

lunar python
#

have you tried putting it in late update

merry sierra
#

yeah its in late update only

rigid island
merry sierra
#

so that the movement will take place first and then it will get update position to spawn

lunar python
#

it looks as if the bullet is coming out a bit slow like the prefab of lazer has its origin set at center and when it is instantiated, half the lazer is behind the muzzle

#

And when the object is instantiated, its next fixedupdate would be called in the next cycle right?

merry sierra
#
private void FixedUpdate()
    {
        if(!isReloading)
        {
            timer += Time.deltaTime;
            if(timer > firerate)
            {
                timer = 0;
                currentMagazine -= 1;

                FireBullet();

                if(currentMagazine <= 0)
                {
                    isReloading = true;
                    reloadtimer = 0;
                }
            }
        }
        else
        {
            reloadtimer += Time.deltaTime;
            if(reloadtimer > reloadingTime)
            {
                reloadtimer = 0;
                timer = 0;
                currentMagazine = maxMagazine;
                isReloading = false;
            }
        }
    }

I put this loop in fixed update

lunar python
#

why is time.delta in fixedupdate

heady iris
#

it's fine

#

Time.deltaTime is set to be Time.fixedDeltaTime whilst FixedUpdate is running

lunar python
#

what there is that feature?

heady iris
#

Imagine the fire rate is set so that you fire 49 times per second

#

you fire on physics update 0

#

at physics update 1, you're almost ready to fire again, but not quite

#

at phyiscs update 2, you fire, and you reset the timer to 0

#

so you only fire 25 times per second

merry sierra
heady iris
#

If you rate of fire can be greater than 50, also consider using a while loop until timer < firerate

#

that way you can fire many times in one step

merry sierra
#

thanks for the help guys

lunar python
#

if you instantiate an object on frame 0, then apply force to it on frame 1, would it takes until frame 2 for physics to take place?

merry sierra
#

🤔

lunar python
#

oh you also apply force on frame 0 so that would make it frame 1?

heady iris
#

Physics updates happen 50 times per second by default.

#

well..it does happen during a frame; it's just that you can have zero, one, or many physics updates happening in a single frame

#

Looks like physics happens before the normal update loop

#

So if you apply a force on frame 0, and Unity decides to run a physics update on frame 1, the force will be used at that point.

lunar python
golden glade
#

I'd like to have a billboard world screen UI facing the camera, however my current issue is that there are multiple cameras (split-screen game), is it possible to make the world screen space Canvas UI with split-screen, if so .. How? If not, what other way would you suggest to show a text above the player which should be the amount of people taken out?

lunar python
rigid island
golden glade
merry sierra
#

is it multiplayer?

golden glade
#

So if I had 4 players, I'd have to spawn 4*4 canvases

golden glade
lunar python
rigid island
#

you're only rendering 1 on each cam, not both

#

give it a try

golden glade
golden glade
heady iris
#

multiple canvases will also work. either way, you need to make sure each player's UI is properly sized.

lunar python
#

i would recommend multiple canvas though. cuz if something change in a canvas, the whole thing gets redrawn

golden glade
#

I already have a canvas for each players view and assigning camera layers per player

heady iris
#

I use one huge canvas for my main menu

golden glade
#

My game already has a performance hit with 2 players running on a 1070 laptop

heady iris
#

I do deactivate almost all of the individual menus, though

golden glade
#

So I'm kind of worried about whether the performance will go down the drain

lunar python
golden glade
#

The game is a 3D co-op "bomberman" like game

#

I have already implemented object pooling so at least thats no issue for now.

rigid island
lunar python
#

the first optimization tip is seriously split canvases

rigid island
#

don't not make something simply for premature optimizing

lunar python
#

my game dont even have canvases yet cuz everytime I add a canvas, the pixels gets jaggy

#

and distorted

golden glade
#

Each player has its own canvas.

I think most of the performance issues comes from unoptimized models thanks to MagicaVoxel.

#

around 4.7M verts in total, and the bombs generate around 500K verts (each).

lunar python
#

wtf

golden glade
#

There are a lot of particles

lunar python
#

where did you even grab those bombs, it could bomb your pc you know?

rigid island
lunar python
#

i remember the 2 million vertices toothbrush in a yandere game

golden glade
#

The bomb model itself is just a sphere model with a flat shader

#

the particles are the issue

lunar python
#

just make a triangle bomb

#

better for performance

golden glade
#

Invisible bomb 🧠

wicked river
#

Hey! I am looking for a fairly standard way to manage variables. Ammo, health, Death state, items collected.

Do I careate a game Manager state and store all the player specific variables in this file and then load and save using this class or do people just shove variables into random classes as they develop and just accept that things might get messy 😅

somber nacelle
#

you put the variables on the objects where it makes sense to have them. for example you wouldn't have both a Player Health and Enemy Health variable on the same object as that would generally not make any sense

lunar python
wicked river
#

Inventory items

lunar python
#

you generally want to have input in seperate files from your player data, just create a player controller for handling external influence, a data manager for each entity, and a input controller

sterile sorrel
#

!code

tawny elkBOT
lunar python
#

you dont want players to be able to directly modify their stats in online games just through their local code

somber nacelle
wicked river
#

I get that. Reason for me asking is, I find that I have randon variables everywhere that the player needs . Stupid example : I have a isDead boolean sitting on a gameState Manager class. I have player health script on a UI component that gets updated via an Event and I have an inventory system set up on a INventoryManager . Now I need to write these data sets to a file to save and load and I find myself looking everywhere trying to keep track of everything. I am 100% going to miss stuff upon saving and loading this way

hardy pendant
#

Hihi I have a question
A video explaining it or a general explanation would be great

So in games, for example stardew valley: after/during a certain triggered event a building in the map changes/upgrades

Whats the simplest way to do this?

sterile sorrel
wicked river
leaden ice
lunar python
#

sounds like recipe for disaster

wicked river
#

I was nooblet when I wrote some of the code. so I am trying to fix my stuff

hardy pendant
lunar python
#

I assume you are an artist getting their hand at game dev right

sterile sorrel
# leaden ice What does that mean? BTW Start is capitalized incorrectly

I just threw that in, in the actual code it's correct

I'm trying to instantiate the trainStat1 prefab in a certain length. It is currently instantiating on any empty game objects with the tag "trainStat1", that works but it does it in other places I don't want it to. So how do I limit the length it instantiates?

hardy pendant
#

Ive dabbled in visual novels quite a bit but I wanted to try my hand at something more hands on

lunar python
#

you could start from learning MouseToWorldPosition to get position of mouse, Raycast to get the gameobject you are pointing at, learn some basic UI stuff to make buttons pop up after click, add functions to buttons and change sprite to desired ones

#

I think thats what you are looking for

lunar python
#

like the click ones that you get from scenes to scenes

hardy pendant
#

Yeah smth like that

Im a studio arts major alongside a creative writing major so it was a pretty naturally coming gateway into game design

lunar python
#

well thats a good start, I guess you already knows most of the basics

leaden ice
lunar python
sterile sorrel
hardy pendant
lunar python
#

like pattern for instantiating?

sterile sorrel
# lunar python i dont quite get what you are meaning

public GameObject[] trainStat1;
public float chunkLength = 90;

void Start ()
{
GameObject[] trainStat1EMPTY = GameObject.FindGameObjectsWithTag("trainStat1");

foreach (GameObject position in trainStat1EMPTY)
{
        int randomIndex = Random.Range(0, trainStat1.Length);
        GameObject randomPrefab = trainStat1[randomIndex];
            Instantiate(randomPrefab, position.transform);
    }

}

In this code, I am Instantiating prefabs into any empty object with the tag trainStat1
that works
but I have separate chunks, so it then spawns into that one and the others too
I need it to only instantiate inside of the chunk length

sick edge
#

Is it better to make base classes or static classes for cross script communication?

lunar python
sterile sorrel
#

you really arent understanding me are you

#

yeah, no nothing helpful there

#

I need it to only instantiate prefabs inside of the chunk length

lunar python
#

the just check if the position.transform.position is inside of chunklength

sterile sorrel
#

and how would i do that?

#

even if i checked that and then let it instintiate it would still instantiate outside of the chunk into others

cobalt goblet
#

Anyone made a distortion 2d mask before or has any idea how I could? Trying to make a distortion/glitch effect that can either fully or partially distort/glitch objects or areas in my viewport?

lunar python
sterile sorrel
#

so how would i do that?

lunar python
#

depends on the object shape

craggy veldt
#

2d or 3d?

golden glade
craggy veldt
#

they're instanced?

#

how many drawcalls?

#

just curious 😌

golden glade
#

4.4k verts before the bomb explosion

craggy veldt
#

OP bomb 👏 it can explode verts counts too 🙌

golden glade
#

Okay, removed all particles. Now it doesn't even go above 10K kekwait

dry mural
#

god, making my own custom implementation of pathfinding using multithreading is such a pain in Unity. (pathfinding must be custom, that's for my thesis)
i'm proud that it's finally working as intended and can handle up to 192 bots queueing path at almost the same time

static matrix
#

oncollision enter also counts if a collider in a child object hits something right?

knotty sun
toxic vault
#

Need some help with mouse aiming in my top down game. It 'almost' works, but there's some bug where it consistently fire off target by a few degrees.

Shooting towards bottom of screen or left of the screen, the bullets feel only very slightly anti-clockwise from my cursor.

Shooting towards the top of screen or right of screen, the bullets are a lot more anti-clockwise from my cursor.

This is my aiming code where I just turn the play to face in direction of where my mouse cursor is.

 Plane playerPlane = new Plane(Vector3.up, transform.position);
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            float hitDist = 0.0f;

            if (playerPlane.Raycast(ray, out hitDist))
            {
                Vector3 targetPoint = ray.GetPoint(hitDist);
                Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
                targetRotation.x = 0;
                targetRotation.z = 0;
                this.transform.rotation = Quaternion.Slerp(this.transform.rotation, targetRotation, rotateSpeed * Time.deltaTime);
            }

And this is code for where I actually shoot out bullets from my gun -

GameObject projectileInstance = Instantiate(projectile, bulletSpawnPoint.transform.position, Quaternion.identity);

            
projectileInstance.transform.rotation = StaticUtilities.GetCrewLeader().gameObject.transform.rotation;
            

            Quaternion pelletRotation = Quaternion.AngleAxis(UnityEngine.Random.Range(-spreadFactor, spreadFactor), Vector3.up) * projectileInstance.transform.rotation;

            projectileInstance.transform.rotation = pelletRotation;
leaden ice
#

You shoulkd never be touching parts of a quaternion like that

#

delete that

latent latch
#

surprised that even works

toxic vault
#

Because I want the rotation only around Y axis. It's top down game, the X and Z rotations for player don't matter

leaden ice
#

Oh this is also wrong

leaden ice
#

but this is wrong:

            if (playerPlane.Raycast(ray, out hitDist))
            {
                Vector3 targetPoint = ray.GetPoint(hitDist);
                Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);```
#

oh wait nvm that's ok

#

just delete that weird quaternion code that is definitely wrong and broken

#

x and z on a quaternion aren't what you think

toxic vault
#

I'll be very honest, Quaternions and angles confuse the heck out of me. A lot of this is copy pasted and modified from other examples on the internet. Maybe some chatGPT mods

leaden ice
#

See if that improves anything

latent latch
#

wouldnt you specify that the z is the up axis though if this is 2D

#

for look rotation

leaden ice
#

I assume 3d top down

latent latch
#

ah ok

leaden ice
#

with gameplay on the x/z plane

fallow flame
#

Hello everyone, not sure if this is the right channel for this but I got a question. I want to make a camera look at and render ONLY a UI canvas, how do i do that?

leaden ice
#

And use a culling mask to make the camera only render that UI

toxic vault
#

No, didn't help. No difference - good or bad

#

What would help with troubleshooting? One thing is the weapon is not centered exactly on the player. Does it need to be?

leaden ice
#

perhaps you should be aiming the gun at the cursor

toxic vault
#

The bullet does rotate in same direction as player though. So weapon being at a wrong angle should not matter?

#

projectileInstance.transform.rotation = StaticUtilities.GetCrewLeader().gameObject.transform.rotation;

fallow flame
#

how do i stop these balls from appearing around my game object??

quartz folio
fallow flame
#

Okay sorry and thank you

leaden ice
toxic vault
#

Yeah, I see that now. My weapon was at a slightly different angle than the player. And the Ray calculation from center of player to cursor. So a lot of slightly whacked calculations

#

First, I am going to make weapon and player angle the same way.

#

Second, in my calculations, I am going to measure from where bullet spawns to the cursor, keeping it all consistent.

#

Let's see how that works out.

rich leaf
#

Hey. I’m curious as to how people here like to approach their inventory systems they design for games. Not looking for a YouTube tutorial as I’ve followed them before.

Just want to hear people’s thoughts on how they approach this (not detailed code but high-level descriptions, ie using scriptable objects for xyz, dictionaries for this, etc)

viscid tide
#

Hey sorry if this sounds dumb but I'm new to this so looking for some help. Basically I have a texture that I need to check every single pixel for it's green value then add it to a float. Since my texture is 1440x1440 pixels it has to do that ~1.9 million times which is way to much. So my idea was to scale down the texture to 100x100 pixel. It will still keep the original texture but just be a worse quality. I did something looking around but I can't find anyway to do this. Would what be the correct approach to achieve this? Thanks!

leaden ice
# rich leaf Hey. I’m curious as to how people here like to approach their inventory systems ...

basically:

  • ScriptableObjects for the "base" data for items, i.e. its name, the UI sprite for it, the effects it has, the max stack size, etc.
  • a serializable, runtime Item class for runtime instances which has a reference to the base data SO, may contain runtime data like durability, use count, etc.
  • As for the inventory itself it depends how you want it to work but it could be anything from a Dictionary<Item, int> to a List<Stack> where Stack is a struct with an item reference and a quantity.
rich leaf
#

Thanks!

lethal rivet
#

Sorry for the code screenshot, but I didn't know how else to show the values during the debug process. As you can see in the variables watcher to the left, leftOffset is 0 but for some reason when I assign it to attached (a RectTransform), it sets it to NaN and it disappears in the scene. Anybody know why this is happening?

leaden ice
#

leftOffset is NaN

#

not 0

lethal rivet
#

Well yeah, but I don't see why that would happen. All the variables that calculate leftOffset are 0, and I'm not dividing by 0 anywhere.

#

One sec

leaden ice
#

x Nan
y -

leaden ice
lethal rivet
#
float leftOffset = positionOffset.x - (sizeOffset.x * anchor.x);```
#

According to VS code positionOffset.x is 0, sizeOffset.x is 0, and anchor.x is 0.

leaden ice
lethal rivet
#

Is VS Code being a little silly and changing NaN to 0 when I hover over a variable?

leaden ice
#

doubtful

lethal rivet
#

guh

leaden ice
#

make sure it's NaN at the moment you're debugging

#

the code could be running multiple times

#

and not be nan every time

lethal rivet
#

I'll check

#

I don't know if this is a valid way to do it, I debug.log Time.time and then collapsed the output to see any repeats and I got no repeats. Does that mean it's only running once per frame? Is there a better way to check?

cosmic rain
lethal rivet
#

I was just checking if a certain piece of code was running more than once per frame, I didn't know how else to do it.

cosmic rain
lethal rivet
#

Didn't know that was a thing.

#

I'll try it

cosmic rain
lethal rivet
#

Ok yeah no repeats.

#

I have absolutely no idea why this is happening. A value is 0, I'm appplying it to a rectTransform then it turns into NaN

cosmic rain
lethal rivet
#

I see. If that's the case I'm just going to do a band-aid patch I don't think I want to debug something happening behind the scenes.

cosmic rain
#

That was just a guess. I don't k ow the whole context.

#

It looks like you had a NAN in the debugger, so it's probably your code and not something internal.

lethal rivet
#

Dang... I'll keep looking I guess.

#

Thank you for your help.

cosmic rain
#

Share the whole script. Maybe there's something obvious.

lethal rivet
#

Sure one moment I’m moving around at an airport

latent latch
#

Negative values probably problematic too beyond zero division but I wouldnt think it turn nan

delicate flax
cosmic rain
#

It's not entirely clear what exactly is being NAN I'm that screenshot. Is attached a rect transform?

lethal rivet
#

Yes

cosmic rain
#

And the pop-up window is of what variable?

lethal rivet
#

My plane is leaving soon so if you see any red flags reply to my message and I’ll get back to it when I land

tawny elkBOT
lethal rivet
swift falcon
#

How do I set up my sprites / tilemaps in unity so the thing that gets shown in front is by the pivot that has a lower Y.

latent latch
#

global transparent sorting axis

swift falcon
#

isn't that just for the Y position? not the pivot

latent latch
#

oh, the pivot you need to do it independently for each sprite in the sprite editor

#

and then on the sprite renderer you sort by pivot

swift falcon
#

oh ok i got it thanks

cosmic rain
hardy pendant
#

hihi I just have one more quick question
ok so im trying to find information on a general concept I want to add to my game but nothings coming up when I look it up so im confused if maybe my english is failing me or if its just not something easy to do?
I want to add favorability bars to my game (if that term rings no bells think like how stardew valley has the heart system or how bg3 has the trust bar)
but I cant seem to find any videos or threads on it?

#

I dont think its a rare concept so im wondering if im just calling it the wrong thing maybe?

rain minnow
#

you won't find a specific tutorial about it since it's just a stat value—shown visually with a bar—used for a custom system in certain games . . .

hardy pendant
#

That actually makes so much sense why didnt I think of that lmao dies

#

thank you btw!

#

(also Approval rating is a way better term than what ive been saying it makes a lot more sense to)

hard viper
#

i have a simple class for a reactive value for this sort of thing

rain minnow
hard viper
#

ReactiveValue<T>, which holds a private field of type T, and public setter. If the public setter tries to set an actually different value, it invokes a public event action, to notify anything that needs to know that the value has changed.

hardy pendant
rain minnow
hard viper
#

i got the idea from Fen or Burrito, I think

#

burrito is especially big on reactivity systems

hard viper
#

approval is more political

hardy pendant
#

yeah I was gonna add both (trust and romance one), but had to sort out what I was actually doing first and it didnt click in my mind that you can just set it up basically like (using Random's example) a HP bar

hard viper
#

a lot of games don’t use a bar/number, and hide the fine details. Usually you only get an indication at specific thresholds

#

more information => min max affection.
less information => more relaxed/vague

chilly surge
#

Oh hey, glad to see more people are adopting reactivity systems 😄

hardy pendant
#

yeah thats true, I just really like how bg3 did it and they used a visible kinda slider-esc bar

hard viper
#

i said his name 3 times, and he popped out of the mirror

hardy pendant
#

LMAO

#

bro was summoned

hard viper
#

KEKW
pretend this server has that emote

hardy pendant
#

I got you lol

#

anyways huge thanks to both you and random, im off now to do the gruelling work that is
✨ designing a city ✨

rain minnow
hard viper
#

it is not worth refactoring, but it is worth making it, and adding it in to anything new

#

it’s just cleaner, and less spaghetti

rain minnow
#

i don't do 🍝 , though, i'll eat it, like i am right now . . .

hard viper
#

fyi, my vanilla reactive value also has a field for default value, to call ResetToDefault

#

default being defined in constructor

#

every variable I want to be a reactive value winds up wanting this behaviour

rain minnow
#

that makes sense . . .

mighty tide
#

love unitys bindings

modern creek
#

When I use a vertical scrollrect with elastic - there's some amount of "buffer" that I can drag past the top of the content. Empirical testing shows it's some.. magic number, about 500 pixels? Is there a way to set/get it programmatically so I don't just have to guess and hope that it works for all sizes?

#

(I'm currently putting a background on the content rect that's top/bottom -600/-600 but I'd prefer to exact-size it)

latent latch
#

seems like something I'd just toss in double its value and call it a day

#

maybe ive done that before actually

agile carbon
#

Hey guys. I’m working on an interesting project simulating cars precisely. So, I have a function that runs and matches up the rotation of the wheels to the speed of the car and vice versa (I’ll take slip into consideration later), but my problem is that when cars steer, the car rotates a little bit as you turn. But in Unity, since I’m custom programming the rotation and movement of the car, I also have to code the rotation of the car. What’s the best way to go about the steering?

#

Rotating the chassis is the greatest problem

modern creek
mighty tide
modern creek
#

but i use these everywhere in my app and the .. lack of a data point to specify the "above-scroller" is kind of annoying

mighty tide
agile carbon
#

Well I guess 4wd is more accueste

mighty tide
#

yeah

#

but it works for most cars

agile carbon
#

So what will happen is my wheels will rotate. Now there is ackermann steering which is based off of a point and then ig there is other steering

#

So if I were to rotate the wheels I could theoretically figure out which way the car should go but figuring out how much it rotates is different

mighty tide
#

basiclly unity's physics will calculate most of it

mighty tide
agile carbon
#

It’s how the chassis rotates

#

And how the back wheels follow the rotation

mighty tide
#

i'm not sure maybe you should look up a youtube video

cosmic rain
merry sierra
thorn stirrup
#

How would I use OnDrawGizmos to draw a circle for a collisionPt?

latent latch
#

if you're debugging points of collision you can always instantiate a gameobject and throw a script onto that that constantly draws the sphere at the location

sterile crown
#

tldr swap triggers

thorn stirrup
#

I understand how to instantiate a new game object in code, but how would i add a script to it programmatically?

latent latch
#

Instantiate(GizmoPrefab, col.gameObject.position, Quaternion.Identity)

thorn stirrup
#

I see

latent latch
#

make a prefab that contains a script for the gizmo

thorn stirrup
#

Ahh duh haha.

latent latch
#

you may want to add its own timer to expire though

thorn stirrup
#

Makes sense

#

Cant i destroy it after a few seconds?

latent latch
#

yeah, the gizmo prefab script can hold all that and destroy itself

#

also, probably parent them to something so they don't spam the scene :)

thorn stirrup
#

Thanks so much for talking through it with me

#

😁

dense estuary
#

I fixed that, however, I am experiencing a problem with my radar where the icon appears within 90 degrees of the ray. Here is my code: cs private void CreateAndMove(Collider collider) { Vector3 colliderPosition = collider.transform.position; Vector3 desiredPosition = colliderPosition - new Vector3(player.transform.position.x, 0, player.transform.position.z); Vector3 position = this.gameObject.transform.TransformPoint(desiredPosition / (scannerRange * transform.localScale.x)); var angle = Vector3.Angle((colliderPosition - player.transform.position).normalized, Vector3.forward); if (Mathf.Abs(angle - ray.transform.rotation.eulerAngles.x) <= 1f) { StartCoroutine(PingDuration()); if (pingVisible) { Instantiate(badGuy, position, transform.rotation, transform); } } Debug.Log("Angle: " + angle); } void RotateRay() { ray.transform.Rotate(0, rotateSpeed * Time.deltaTime, 0); }
Is there a version of Vector3.angle that is always a value between 0 and 360?
(I know its been like 14 days, I'm sorry.)

round magnet
ocean hollow
round magnet
somber nacelle
#

you are creating and destroying a brand new Texture2D every single time you call this
just reuse the Texture2D object

ocean hollow
somber nacelle
mild holly
ocean hollow
somber nacelle
#

okay and how often do you start this coroutine

mild holly
#

The interactable object implements two interfaces

ocean hollow
somber nacelle
ocean hollow
somber nacelle
#

none of what you have said would prevent you from reusing a Texture2D that you create instead of creating and destroying one every frame. you create a ton of garbage by doing that

mental rover
ocean hollow
# somber nacelle none of what you have said would prevent you from reusing a Texture2D that you c...
private IEnumerator PickColorCoroutine()
        {
            // Wait until all rendering is complete
            yield return new WaitForEndOfFrame();

            if (tempTexture == null)
            {
                tempTexture = new Texture2D(1, 1, TextureFormat.RGBA32, false);
            }

            // Calculate the correct position to read from based on the mouse position
            Vector2 mousePosition = Input.mousePosition;
            Rect readPixelRect = new Rect(mousePosition.x, Screen.height - mousePosition.y, 1, 1);

            // Read the pixel from the RenderTexture
            tempTexture.ReadPixels(readPixelRect, 0, 0);
            tempTexture.Apply();

            // Retrieve the color from the texture
            Color pickedColor = tempTexture.GetPixel(0, 0);

            // Set the brush color
            brush.Color = pickedColor;

            foreach (Renderer visualizer in colorVisualizers)
            {
                if (visualizer != null)
                {
                    visualizer.material.color = pickedColor;
                }
            }
        }

i couldve sworn i implemented this before i went with my current solution (i did) and my frames still tank by the same amount

swift falcon
#

how do I stop this from happening? (this referring to the light overlapping the object and going through it.)
my object has a collider.

now i would try a shadow cast but it doesn't work great either (as you can see in second pic), like i want the light to follow the red lines and not light up the object like that

swift falcon
#

well

next salmon
#

In no dimensions do shadows look like what you want them to

swift falcon
#

i know

#

im not trying to make it a light

#

im trying to make it a field of view marker

next salmon
#

Its still right

swift falcon
#

not really. if you stand behind a door way you will see a somewhat straight line

#

it doesnt expand unless you are really close to it

mellow sigil
#

The second screenshot is accurate to how the line of sight would work in real life. If you want something different you'll have to code it yourself

dense tapir
#

hey guys?

anyone can say me what i need todo, that i can fold in and out the Headers in inspector?

tawny elkBOT
dense tapir
thin aurora
dense tapir
#

if i turn the dark mode then the highlighted colors are normal xD but that broke my eyes xD

so pls dont try to find any problems where i dont need/have help/problem

thin aurora
#

It's not about finding irrelevant problems, you're expected to have a configured editor if you want to receive help. It also benefits you as the user a lot to have everything set up correctly.

dense tapir
knotty sun
dense tapir
deft timber
thin aurora
deft timber
chilly surge
# thin aurora Common Unity types are not correctly highlighted so your editor is not configure...

FYI if they are using VS Code and using a theme that does not support semantic highlighting or turned off semantic highlighting altogether, then it falls back to simple TexMate grammar based syntax highlighting and will not highlight Unity types differently because it won't have syntax information. Not saying that's definitely the case here, just saying it doesn't always mean IDE is not configured.

thin aurora
#

Interesting, I never seen that happen but that sounds reasonable behavior from VSCode

chilly surge
#

In VS Code you can even turn off all highlighting so it's just black and white, but still have full language server diagnostics and error reporting. It's extremely configurable.

fathom patrol
#

Hi all! What would be the best and safest way to insert something into a MySql database running on a server from a standalone Unity Application?

quartz folio
#

It annoys me when you can't tell value types from reference types, let alone not even differentiating types from members

knotty sun
fathom patrol
#

do you have any sources for getting started with that? I'm not that familliar with web-development

knotty sun
#

what OS is your database running on?

fathom patrol
#

Ubuntu Server

#

Ubuntu 22.04.4 LTS x86_64

dense tapir
chilly surge
# quartz folio Sounds awful lol

Yeah realistically no one sane would do that and just use semantic highlighting like a normal person. But having TexMate grammar highlighting is what allows VS Code to give (not very good but better than nothing) syntax highlighting for practically every popular language and file format in the world without having a language server for every single one of them.

knotty sun
#

Ok, then probably Node.js is best for you. it has easy access to both http and MySQL
https://nodejs.org/en
https://www.w3schools.com/nodejs/nodejs_mysql.asp
https://www.w3schools.com/nodejs/nodejs_http.asp

chilly surge
#

It also allows me to open a 1 million LoC C# file (artifacts, not actually source code) in less than a second and have good enough syntax highlighting to work with, rather than having to wait for language server to slowly process the entire file. VS could never do that.

thin aurora
#

.NET has solid support for MySQL and also things like PostgreSQL and SQLite. There's a general framework that's "usually" used called Entity Framework which provides a code-first solution to database communication and it makes it super easy to work with.

fathom patrol
#

i see - thank you both!

wild warren
#

i have two web requests in unity, one of them gets back an image url from the internet the other one downloads it and turns it to a texture, my problem is the second one doesn't wait for the first to fetch

wild warren
# leaden ice What makes you think that?

i run the code, it gets to the second part and it gives me n error says it cant fetch url or whatever because it's empty and then after a while the url is generated

knotty sun
#

wdym 'the url is generated' ?

wild warren
# knotty sun wdym 'the url is generated' ?

okay let me explain this further, i'm using amazon s3 bucket to store users profile picture, my bucket is private which means i can't fetch images directly from there, so for that i wrote an api in nodejs, to access the image and create me a temporary url for that image, in unity first i run that api to fetch the url and then i need to download it to display the image as a raw image texture,

knotty sun
wild warren
#

i call the first part which is getting the image url, then i call gettexture to download the url and display it as texture, but if you look at the console log it ran the second part then the url got fetched

knotty sun
# wild warren

this does not seem to be in any way related to the code you posted

wild warren
long hare
#

why the pixel perfect is showign up like this ?

knotty sun
#

you've made it worse, the second coroutine will run before the first has completed.
Also how do you expect us to help you if you do not provide correct code

leaden ice
long hare
#

these are the options for the pixel perfect

wild warren
#

@knotty sun @leaden ice okay here is the orginal code and it's still the same.

knotty sun
wild warren
deft timber
south violet
#

Hey, Im using URP and I have a Camera which is disabled and I render its view to RenderTexture using camera.Render().
The problem is it renders Gizmos as well. How can I prevent it?

brave shadow
#

how do i save my game so then i can covert it into zip and sumbit it into the dropbox

leaden ice
#

Which Dropbox?

brave shadow
#

@leaden ice

#

@leaden ice

leaden ice
#

This is honestly a question for your teacher

brave shadow
#

@leaden ice

leaden ice
# brave shadow both

Then make a build and put the build folder and the project folder into a zip archive together, what's the issue

brave shadow
#

as i open it says made with unity then a blank template ;-;

leaden ice
#

Sounds like you didn't build the game properly

#

Probably didn't include your scenes

brave shadow
#

i did..

brave shadow
#

so the teacher can look throught the file

leaden ice
#

That's what I explained how to do

#

I don't see what's complicated here

leaden ice
#

Show us

brave shadow
#

not the game like whole stuff

leaden ice
#

put it in the Zip

#

Whatever you want to share, put it in the Zip

brave shadow
#

bro there is like some useless files in my fodler

#

folder

#

@leaden ice

leaden ice
brave shadow
#

IDK..

upper pilot
#

😄

leaden ice
#

Why don't you know

#

Just look

upper pilot
#

it is default empty scene probably

leaden ice
#

If you don't know why did you include it in the build?

upper pilot
#

so when you compile, the game starts in that scene and nothing happens

brave shadow
#

NVM I FIXED IT

#

SO LIKE..

#

HOW DO I SHARE MY PROJECT

#

THIS IS THE GAME

leaden ice
#

Zip it

brave shadow
#

I WANNA SHARE THE FILE

leaden ice
#

Yes zip the file

#

Whatever you want to share, zip it lmao

brave shadow
#

This one right?

leaden ice
#

That's the build

upper pilot
#

Do you know what zip/rar is?

#

Take whole thing and pack it

#

all files

leaden ice
#

None of this is code related BTW

brave shadow
#

💀

leaden ice
#

It's your project and your computer

#

Where'd you put it?

brave shadow
#

should i just upload the game?

#

💀

leaden ice
#

You should talk to your teacher not us.

brave shadow
#

ok

cosmic rain
agile carbon
#

You can’t rotate the car in the direction until the car moced

#

And at that point you are going in increments so I would need to calculate the amount it needs to rotate and then do it per frame

#

But simultaneously get the direction in which the wheels need to move as well as make the back wheels follow

sturdy gorge
#

For some reason I'm facing this issue. Where I update variables in my code it doesn't reflect on the unity hub. The DeadZone here is -30 but it is reflecting -20 on the UI.

#

No idea why this is happening.

oblique spoke
heady iris
#
public float florp = 100;

This declares a field named florp with a field initializer that sets it to 100.

#

Field initializers are applied during the creation of the object.

#

Unity applies serialized values after the object is created.

#

"serialized" meaning "saved", basically

#

anything that shows up in the inspector (if you aren't doing any Wacky Custom Editors, at least) is a serialized value

#

The field initializer will only matter when creating new instances of the component, or when you right click the component and hit "Reset"

sturdy gorge
oblique spoke
#

Fen explained it in detail. Values in the Unity editor override those default values in code.

heady iris
#

suppose I create a component called "Example"

#
using UnityEngine;

public class Example : MonoBehaviour
{
    public float myField = 123;
}
#

When I attach the "Example" component to a game object, Unity stores some data.

#

you can actually just drag a scene or prefab aset into a text editor to look at it

#
MonoBehaviour:
  // a bunch of other junk
  m_Script: {fileID: 11500000, guid: 816d62879a223453490b2d4b131c57d0, type: 3}
  myField: 123
#

Unity records that "myField" contains a value of 123

#

If I then edit the value in the inspector, the serialized data changes.

#

so if I change "myField" to 100, it remembers the value.

#
MonoBehaviour:
  // a bunch of other junk
  m_Script: {fileID: 11500000, guid: 816d62879a223453490b2d4b131c57d0, type: 3}
  myField: 100
#

That's what it means to be "serialized": the data is stored.

#

If I made that "myField" private, then:

#
  • myField would not appear in the scene or prefab data at all
  • Unity would not remember a value for myField
  • myField would not show up in the inspector
#

Unity has to turn this scene or prefab data into actual objects.

#

It does this by:

  1. Creating the object
  2. Assigning all of the serialized values into it
heady iris
heady iris
sturdy gorge
#

So, it basically stores the value that I assign first time (which is called serialization)?

So, if I do public float myField = 123; I will have to reset every time?

heady iris
#

If you don't want Unity to remember a value for each instance of your component, you should tell it to not serialize the field at all.

#

By default, private fields aren't serialized.

#

You can use also use the [System.NonSerialized] attribute.

sturdy gorge
#

Yes, but private won't be present in the inspector. Right?

#

So, change it from code every time.

heady iris
#

since unity doesn't save it, there'd be no point in displaying it in the inspector: you couldn't do anything to it

sturdy gorge
#

I'm not sure if thinking in that terms is good.

heady iris
#

yes, that's not the right way to approach the inspector

#

The inspector is used to configure components.

#

You create scenes and prefabs that contain GameObjects. GameObjects have Components attached to them.

#

Components have serialized fields that you assign values and references to.

sturdy gorge
#

Okay, but say I did some stuff on the inspector like changing the value and now I found the ideal settings. Now I wanna 'save' that. Say the code is present on github. Saving won't happen right? Since the code still has value 10 while in the inspector say I changed the value to 15.

heady iris
#

version control isn't relevant here at all

#

If you want to change the default value the field will have when you create new instances of the component, then change the field initializer

#

This won't affect any existing instances.

#

so if you decide you want myField to default to 15, change it to public float myField = 15;

#

Any new instances of your component will start out with a value of 15.

sturdy gorge
#

This is confusing kind of lol

oblique spoke
heady iris
#

well, no, they just live in the actual scene and prefab assets

heady iris
#

That's all.

sturdy gorge
heady iris
#

i don't know what you mean.

sturdy gorge
#

Say pull my code and test it.

heady iris
#

Do you mean if they check out your project from source control and open the editor?

heady iris
heady iris
#

The serialized values are part of the scene or prefab. Scenes and prefabs are assets. Assets are put into source control.

oblique spoke
#

All of that stuff should be replicated through version control. Only personal editor preferences and caching files may be left out.

sturdy gorge
heady iris
sturdy gorge
#

Okay, that makes sense.

heady iris
#

Unity would be completely unusable if you couldn't make changes to scenes and prefabs (:

sturdy gorge
#

Yeah, I am just trying to relate it with core dev stuff that I do at work. Here, from my understanding so far, the inspector matters a lot compared to dev. So, you dw reset it after you change a variable in the code I'm assuming.

heady iris
#

If you want to discard the serialized data for that specific instance of the component, then yes, you'd reset it.

sturdy gorge
#

So, if I want to apply the values that are in the code. I'll have to press reset everytime?

sturdy gorge
heady iris
#

If you don't want to serialize the field, then mark it non-serialized.

#

The inspector is used to configure an object. It's not intended to be a list of every single field the class has.

sturdy gorge
#

Okay, got it. Thanks for the help.

heady iris
#

You can read more about how serialization works here.

dusky lake
#

Hey, im using a roslyn code generator to generate this sample class right here:

using UnityEngine;

namespace EntityFramework {
    public class ComponentList {
        public static void Main() {
            Debug.Log("");
        }
    }
}```

Whenever i generate it though it gives me this: https://img.sidia.net/ZEyI5/DOyUwaCa97.png/raw (Show references: https://img.sidia.net/ZEyI5/nozaRopu17.png/raw)

There is only one file, if I modify it by hand it is the same regardless of what reference i follow

This is the code generator: https://gdl.space/tozaqozoke.cs
south violet
#

Hey, Im using URP and I have a Camera which is disabled and I render its view to RenderTexture using camera.Render().
The problem is it renders Gizmos as well. How can I prevent it?

dense tapir
mellow imp
#

why do we use InvokeRepeating() in void Start() instead of void Update()I never understood the reason behind that.

spring creek
#

You can use it in either

#

But probably shouldn't use it at all

#

Use coroutines instead

#

Or just CALL the method in update I guess

mellow imp
#

and for some reason they use invokerepeating in start rather than update

#

like it can still be multiplied by time.deltatime so i dont understand why that is

spring creek
mellow imp
heady iris
#

read the documentation for the methods you are using

past barn
#

InvokeRepeating and Execution stuff

heady iris
#

you should get used to doing this; using tools without actually knowing what they do is going to make game development completely miserable

mellow imp
mellow imp
#

i will keep that in mind

violet junco
#

Hi devs! I don't suppose someone could impart their wisdom and help me with something? I am trying to make my first person character controller work with an Xbox controller. I have everything working with PC but when I connect my controller, my movement and jump is already set up, but I need to find a way of getting the right analogue stick to work with the camera. Would anyone be able to help me out with getting this to work? I'm hoping that once learning this, I can teach future students with this method for their projects 🙂 TIA!

sage latch
violet junco
sage latch
violet junco
silver cloud
#

I'm wondering, is there some way to programatically change width and height of a RenderTexture with a downscaled resolution (e.g. 192x108 for 1920x1080 display) whilst keeping the size same for just larger scales of a resolution (e.g. still 192x108 for 3840x2160)?

heady iris
#

I don't understand what the goal is here. Don't you just want it to be a constant 192x108, then?

#

Or do you want lower values for smaller initial resolutions?

silver cloud
#

I want it to be 16:10 when the display is 16:10

leaden ice
#

you can also just make a new one based on some calculation

heady iris
#

with a roughly constant total amount of pixels?

silver cloud
#

no, I meant an aspect ratio to match the display

#

How do I make the calculations?

heady iris
#

so you need to solve for width * height = total and width * ratio = height

#

two unknowns, two equations

silver cloud
#

ok

heady iris
#

width = height / ratio, so you get height * height / ratio = total

#

height = sqrt(total / ratio)

given that, you can get

width = total / height

#

there will be some rounding error here

#

so you might not get exactly total pixels

silver cloud
#

so I floor that?

heady iris
#

I would round it, I guess

silver cloud
#

ok

dense tapir
worthy willow
#

My NavMeshAgent AI follows a waypoint in the Update function, but if the Waypoints Y value is too high (over 2.4 I think) it stops following the waypoint. Is there a way around this?

hexed pecan
#

Might wanna snap the waypoint position onto the navmesh with NavMesh.SamplePosition

worthy willow
#

lol as soon as I posted this I thought about just making a new vector3 thats the waypoint x and z values only and Y is kept at 0 and it gives the result I want

#

thanks for your input though

worthy willow
hexed pecan
#

So I would still use SamplePosition

solemn raven
#

Hi
is it possible to make a custom editor for classes that is not inherited from monobehaviour ?

hexed pecan
#

Unless it is a scriptableobject or something

solemn raven
#

@hexed pecan I just wanna mention it on other script
i have script called "Setup" which has a custom editor , inside this script I mention another class that is not monobehaviou public Writer writer; the custom editor of main has this line EditorGUILayout.PropertyField(writer); ... << this line is returning error "NullReferenceException: Object reference not set to an instance of an object"

#

I found that if I made writer a monobehaviour the problem is gone

solemn raven
#

also if I remove the custom editor the problem is also gone

solemn raven
hexed pecan
#

Ok I thought you wanted to show the variables

#

You want it to be draggable?

solemn raven
hexed pecan
#

Okay then Writer should be a MonoBehaviour or a ScriptableObject

solemn raven
#

no other way around it ?

#

I'll have to added monoBehaviour just for that ?

hexed pecan
#

Well, where would you drag it from if it wasn't a mono or SO?

solemn raven
solemn raven
#

i thought something is missing in my editor

hexed pecan
#

Not sure

warped orchid
#

!code

tawny elkBOT
tired moss
#

Hi, I'm really not sure where to ask this or what to do about it, so I'm asking here. I'm trying to lerp the feet's position to anchors that follow the hips after they reach a certain angle difference. The first problem I have is managing correct movement timing; I'm looking to make each feet move if the opposite is grounded. I also have issues with moving the character while lerping the feet, as they use an incorrect world position, and makes feet go to an old position. The last issue can seen at about 00:46.

Currently using animation rigging for the head, neck, and hip look direction, and code for making the feet face the correct direction. Any help or tips are greatly appreciated :)

distant pasture
#

thinking of implementing a restart button intra scene: can I just do my script for go to x scene and choose the current one and it'll restart? we have no other scripts to save from scene to scene so i'd imagine it would just restart if I do this, but I'm new to unity so im not sure

tired moss
rigid island
#

link it inside the inspector so you know its fully connected

sly igloo
sly igloo
rigid island
#

Ohh I never used that in script sry

sly igloo
clear halo
#

Hi. I want to make a card game and I'm having trouble with revealing cards.
They're supposed to reveal in a certain order, but they all get revealed at once. I tried putting WaitForSeconds(), but they still get revealed at the same time.
This is the loop that handles this. The Reveal() function just flips it and makes the parameter isRevealed true.

for (int j = 0; j < cardCount; j++)
        {

            GameObject localCard = cardSlots.transform.GetChild(j).gameObject; //Find the unrevealed card

            if (localCard.GetComponent<CardProprieties>().playedOnTurn == currentTurn.Value)
            {
                yield return new WaitForSeconds(1); //wait 1 second

                localCard.GetComponent<CardProprieties>().Reveal(); //Reveal card

                int cardPower = localCard.GetComponent<CardProprieties>().currentPower;

                if (side == 0) 
                {
                    location.GetComponent<LocationClass>().localPower += cardPower;
                }
                else
                {
                    location.GetComponent<LocationClass>().enemyPower += cardPower;
                }

            }
        }
sly igloo
clear halo
#

That for is in a coroutine

neon zinc
#

I have a problem and I want to know if someone can help me. I have a GameController that use Singleton so it has the DontDestroyOnLoad(gameObject); code. But when I change from one scene to another scene that have a GameController, the new GameController is replaced by the GameController from the scene before. This provoke that all the references from the objects in the new scene that use methods of the GameController are broken and missing. Sorry if this is a bit confusing, but if someone understand it, how can I solve it?

hard viper
#

what singleton class are you using?

hard viper
neon zinc
hard viper
#
  1. that is why is is destroyed
  2. use the singleton class I sent you
#

it would be
public class GameController : Singleton<GameController> {

#

this singleton derives from monobehaviour

neon zinc
#

Ok, I will take a look of it, thank u so much

neon zinc
neon zinc
hard viper
#

ty. i got it from someone else, and made small modifications to it

grave tundra
#

That's remarkably similar to my SingletonBehavior

#

Wow heh.

using UnityEngine;
using JF.Logger;

namespace JF.UnityCore.Behaviour {

    /// <summary>
    /// A singleton Monobehaviour that automatically creates an instance of itself the first time instance is referenced
    /// </summary>
    abstract public class JFAutoSingletonBehaviour<T> : MonoBehaviour where T : MonoBehaviour {

        public static T instance {
            get {
                if (_instance == null) {
                    // First try to find the instance in the scene.
                    _instance = FindObjectOfType<T>();

                    // If the instance doesn't exist, create a new gameobject and add the component
                    if (_instance == null) {
                        GameObject obj = new GameObject(typeof(T).ToString());
                        _instance = obj.AddComponent<T>();
                    }
                }

                return _instance;
            }
        }

        private static T _instance;

        virtual protected void Awake() {
            if (_instance == null) {
                _instance = this as T;
            } else if (_instance != this) {
                JFLogger.Error(
                    new string[] { "JFAutoSingletonBehaviour", typeof(T).ToString() },
                    "There can only be one instance of type {0}. This MonoBehaviour will be destroyed", typeof(T).ToString()
                );
                Destroy(this);
            }
        }

    }

}
#

Like, eerily similar haha

golden garnet
#

Hey guys. Asked this a couple times before but got no solid answer. Lemme try again... Does anyone have any idea how to fix this?

#

hastebin link is dead now but i could resend if needed

hard viper
grave tundra
#

Yeah i see that in the other example

hard viper
#

my game had some infinite loop crashes as it closed instead of closing properly as a result

grave tundra
#

You know, I have had a couple infinite loops for no reason recently

hard viper
#

That will do it

#

that is why i also have TryGetInstance

#

TryGetInstance tries to get the instance, but does NOT try to make a new instance if it can’t find it.

#

I only call TryGetInstance in things like OnDisable, OnDestroy, and related to avoid infinite loop shenanigans

grave tundra
#

I appreciate the examplanation, I'll add it.

hard viper
#

one last little thing: a lot of people like their singletons to be automatically DontDestroyOnLoad

#

My game has >50 singletons, and only 2 are DontDestroyOnLoad

grave tundra
#

Yeah, I just usually put it in Awake of the singleon itself

#
        override protected void Awake() {
            base.Awake();
            DontDestroyOnLoad(this);
        }
hard viper
#

Yeah. Definitely do NOT copy that from my implementation. I’m stuck with it because I don’t want to refactor.

grave tundra
#

Haha you could refactor in like 20 mins if you bite the bullet 😄

hard viper
#

yeah, but i don’t feel like it lol

#

the only parts that are actually important are the ones i mentioned about app quit and trygetinstance

grave tundra
#

Yeah I added those to my like 7 year old file, thanks! 😄

#

I think I've gotten kinda lucky since I don't often tear these down

hard viper
#

Is there a specific component needed for TMP Input Field to work?

#

i put down a gameobject with a TMP Input Field component, but I think there is something else missing

latent latch
#

create it from the asset menu

grave tundra
#

Perhaps a silly question here: do I need to cache results from Addressables.LoadAssetAsync, or will unity handle that?

latent latch
#
m_LogoLoadOpHandle = Addressables.LoadAssetAsync<Sprite>(m_LogoAddress);
m_LogoLoadOpHandle.Completed += OnLogoLoadComplete;

private void OnLogoLoadComplete(AsyncOperationHandle<Sprite> asyncOperationHandle)
{
    if (asyncOperationHandle.Status == AsyncOperationStatus.Succeeded)
    {
        m_gameLogoImage.sprite = asyncOperationHandle.Result;
    }
}
grave tundra
#

Not exactly. I mean what I load the same asset many times (say a reused tree prefab)...

mighty juniper
#

Hey all. I'm trying to setup object pooling for the first time and this was my attempt at setting up a system that allows for it to be relatively expandable with multiple pools, curious on your guys' opinion. Whether i've done any bad practices, how I could potentially improve, etc. Thanks

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

public sealed class ObjectPool : MonoBehaviour
{
    public static ObjectPool instance;

    private void Awake()
    {
        if(instance == null) instance = this;
    }


    [System.Serializable]
    public sealed class Pool
    {        
        [HideInInspector] public GameObject[] objects;

        public int count;
        public GameObject prefab;
        public string identifier;

        public void CreatePool()
        {
            objects = new GameObject[count];
            for(int i = 0; i < count; i++)
            {
                GameObject obj = Instantiate(prefab);
                obj.transform.parent = instance.transform;
                obj.SetActive(false);
                objects[i] = obj;
            }
        }

        public Pool(string identifier, GameObject prefab, int count)
        {
            this.identifier = identifier;
            this.prefab = prefab;
            this.count = count;

            CreatePool();
        }
    }

    [SerializeField] private List<Pool> objectPools;

    private void Start()
    {
        foreach (Pool pool in objectPools)
        {
            pool.CreatePool();   
        }
    }

    public void AddPool(string identifier, GameObject prefab, int count)
    {
        objectPools.Add(new(identifier, prefab, count));
    }

    public GameObject GetPooledObject(string poolIdentifier)
    {
        Pool pool = objectPools.FirstOrDefault(p => p.identifier.ToLower() == poolIdentifier.ToLower());
        if(pool == null) return null;

        return pool.objects.FirstOrDefault(obj => obj.activeInHierarchy);
    }

}
lean sail
#

if you wanted to stay with yours,
i suggest getting away from using a string for the ID. Maybe you can just use the prefab as an ID
then you can use a Dictionary<GameObject, Pool> instead of having to search through a list to find the pool you want

mighty juniper
#

Oh alright, thank you.

mighty juniper
lean sail
#

also instead of checking which is activeInHierarchy, you can keep a collection of objects only usable in the pool. Remove them from the pool as they are gotten, then have them returned when they are finished being used. This way you've immediately gotten rid of searching through objectPools and searching through the pool itself

lean sail
mighty juniper
#

Makes sense thanks again

mighty juniper
lean sail
latent latch
#

ye should just stick to a specific type for each pool

lean sail
#

Also its the same like how you are using a string for the ID, you could remove that string entirely and just compare the prefab

latent latch
#

Pool<T>
public T prefab;

mighty juniper
#

Gotcha, working on implementing it now

latent latch
#

It's more that GameObject itself is pretty ambiguous, even if you know what's to be stored in it. Usually you want pools to be quick and direct at what they're distributing.

vagrant blade
#

Finer control. But if you're new, a rigidbody is "easier" to move, you just point and launch it.

rigid island
#

you can have more control over cc without worrying too much about collision detection

#

kinematic can give you control as much but then you need your own detections for wall

twilit scaffold
#

Anyone know why childRectTransformMaximumSize; is a different color than the rest? It is used shortly after this declaration

#

Bah. It is never actually used, even though a value is assigned in Start. i forgot i changed that calculation

rigid island
#

yeah assigning a value doesn't necessarily mean its being used

sleek heath
#

CharacterController has other little goodies which rigidbody doesn't have

#

cc is good for if you want a player controller that does everything you want out of the box

ocean hill
#

UnityEditor.dll assembly is referenced by user code, but this is not allowed.
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)

can anyone help me for resolve this problem

#

i already did checked all my script for UnityEditor Reference or not ,, but after i resolve it , same error happen