#archived-code-general

1 messages · Page 119 of 1

lean sail
#

i didnt really look at how this time is given, if its per frame then lag spikes wont change anything. If its grabbing the time from somewhere then yea can be an issue

idle flax
#

This is how I define the time

TimeOfDay += Time.deltaTime * timeSpeed;
TimeOfDay %= 24;
lean sail
#

ah yea then just store the int as suggested

ashen yoke
idle flax
ashen yoke
#

give me a sec i had an example of proper accumulation

#

yeah seems i got time accumulation from time system confused with time accumulatior errors from ticker

#

with a ticker you cant just += delta you have to compensate for tick overshoot

#

with just a time system its fine, according to my old code

idle flax
#

All right.

mystic yoke
#

You just need to -= the duration instead of setting to zero when you tick over

#

A mod works just as well since it preserves the remainder

swift falcon
#

ty

ashen yoke
#

yes i vaguely remember all that but it was long ago so its foggy

mystic yoke
#

Lost in time like tears in rain?

ashen yoke
#

only to resurface when i need a ticker again

#

but then ill just copy old code

mystic yoke
#

I need to organize my snippets better, I keep having to redo stuff bc I forget where I solved it the first time

ashen yoke
#

and i dont have to copy, i already have Ticker class in utils lol

#
            float time = GetTime();
            if (lastTick + Tickrate < time)
            {
                DeltaTime = time - lastTick;
                lastTick = time;
                ++TotalTicks;
                return true;
            }

this isnt correct ticker tho

mystic yoke
# idle flax What should I do instead?

If you want to detect whether a new hour has passed regardless of tick rate, check for the delta change rather than the real number

In other words, save the previous tick and compare the hour of that tick to the hour of the current tick, and emit an event if they're different.

#

If you want to be sure you will never miss an event (eg. If you think it is possible to skip an hour between ticks for some reason), you can loop over the difference between the two, adding 1 hour each time, until you catch up to the present

#

In most cases that loop will only execute once ofc

#

This becomes useful if you have a hyperspeed fast-forward feature for example

#

It's also the basis for how the fixedupdate loop works

idle flax
#

I see, that's very useful, thanks.

ashen yoke
#

found it

#
protected override void Tick(float dt)
        {
            // Get Scaled Time Passed
            double scaled = Time.deltaTime;
            totalTimePassed += scaled;

            ulong ticksPassed = (ulong)(totalTimePassed / SR.DT_NORMAL);
            if (ticksPassed != lastTicksPassed)
            {
                int ticksToAdvance = (int)(ticksPassed - lastTicksPassed);
                for (int i = 0; i < ticksToAdvance; i++)
                {
                    tick++;

                    foreach (var tmono in registered)
                    {
                        ulong lastTick = tmono.LastTick;
                        TickRate tickRate = tmono.TickRate;

                        if (tickRate == TickRate.EveryFrame)
                        {
                            if(tmono!=null) tmono.Tick_Int(Time.deltaTime, tick);
                            continue;
                        }

                        ulong tmonoTicksToAdvance = (ulong) SR.GetTicksToAdvance(tickRate);

                        if (tick - lastTick >= tmonoTicksToAdvance)
                        {
                            tmono.Tick_Int(SR.DT_NORMAL * tmonoTicksToAdvance, tick);
                        }
                    }
                }
                lastTicksPassed = ticksPassed;
            }
        }
#

jesus, good thing nobody ever seen this

mystic yoke
#

Not anymore

stable rivet
#

I'm trying to make a small, catapult-style flight arcade game and I'm struggling to figure out flight. After being flung, the player will fly similar to how a paper airplane might - being able to angle up to gain some altitude but sacrificing speed, and vice versa. I'm struggling to figure out the best way to approach this. Using physics would make my life a whole lot easier, but would then require having the player actually move, which seems insane for a flight game.

Does anyone have any experience with this? 😄

heady iris
#

"having the player actually move" seems like a prerequisite for a flight game...

mystic yoke
ashen yoke
#

yeah physics work in the parents frame of reference

stable rivet
ashen yoke
#

why does it seem insane

mystic yoke
#

Floating point precision id assume

ashen yoke
#

the assumption is clear

#

maybe its something trivial, like camera

#

"having the player actually move" is weird sentence

mystic yoke
#

As opposed to keeping the player fixed and moving the background

lean sail
#

Seems like the game idea very much revolves around physics too

mystic yoke
#

Like flappy bird

stable rivet
#

Pretty much what Mad said

mystic yoke
#

I think it'd be conceptually simpler to move the player in this case

stable rivet
#

Yeah, you're right - thanks!

neon bolt
#

!code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

mystic yoke
#

As for the plane physics, break down the forces involved. As the nose tips up or down, increase the force of gravity proportionally.

When moving upwards, gravity will cancel out the forwards momentum. When moving downwards, it will compound onto the forwards momentum

stable rivet
# neon bolt !code

no code worth showing yet, just wanted input on the 2 different approaches and any major pitfalls

mystic yoke
#

When moving flat, gravity can be basically 0, or some minimum value

neon bolt
#

no thats my bad sorry, just wanted to know how to post XD

stable rivet
#

I knew that a player nosediving and then leveling out should affect forward momentum, but didn't really know how to calculate it

mystic yoke
#

Then just make sure your plane is pointing in the direction of the velocity and it should make a decently convincing effect

stable rivet
swift falcon
mystic yoke
#

If the player tips the plane up and it starts losing speed, you want the plane nose to naturally tip downwards as it loses enough speed

#

That will happen if you track the plane onto the velocity vector

vague slate
#

Is there a way to call Input method for mouse wheel without using string?

mystic yoke
vague slate
#

yeah, i want to use in burst

mystic yoke
#

Input.mouseScrollDelta

vague slate
#

oh, nice

#

what's the correct axis? x or y?

mystic yoke
#

Y

vague slate
#

thanks

neon bolt
#

im trying to instantiate a game object with a specific rotation but am cant seem to get the object to face the right direction. I think the issue might be with my use of quaternions but I'm very confused by them. any suggestions

mystic yoke
#

Can you describe the specific direction you're trying to achieve

neon bolt
#

i have two versions of the functions, one where I manually set the direction with a vector and the other that is based on mouse position

#

this is for a 2D game

#

so I just want to change the z axis

mystic yoke
#

What is it currently doing wrong

neon bolt
#

the objects dot spawn with the correct rotation at all.

#

Ive tried setting the eular manually to 0, 0, 1 and i get a rotation of -57

ashen yoke
#

probably the issue with Camera.main.ScreenToWorldPoint(Input.mousePosition)

#

you need to set the z in Input.mousePosition

#

is it 2d?

neon bolt
#

yeah

ashen yoke
#
var mp = Input.mousePosition;
mp.z = 0;
Camera.main.ScreenToWorldPoint(mp);
#

assuming your gameplay is happening at 0 z

neon bolt
#

ive tried setting spawnedAttack.transform.rotation = quaternion.Euler(0, 0, angle); to be spawnedAttack.transform.rotation = quaternion.Euler(0, 0, 1); so that im not using the mouse position atall and it still gave me the wrong z rot

#

yeah it is, ill try that now

ashen yoke
#

thats not it probably now looking at the rest of the code

hexed pecan
#

ScreenToWorldPoint returns a value

ashen yoke
#

and it should be 0

#

ill just go im useless today

neon bolt
#

hahaha thank you for trying anyways

ashen yoke
#

to clarify - the z should be the distance from camera near frustum plane to the actual world point you want to sample

#

in case of 3d perspective camera

#

i dont know how it behaves with ortho

neon bolt
#

I work with all my objects set to 0 on the z axis

ashen yoke
#

so when you do

Vector3 lookDir = mousePos - spawnTarget.transform.position;

you are getting a direction vector that points somewhere off the plane where game is happening

#

if the camera is at z 5, its gonna point towards the camera

#

assuming in 2d it uses near camera plane

mystic yoke
#

Ortho works the same for the record

ashen yoke
#

then yes you have to set mousePosition.z to camera.position.z * -1

bitter hound
mystic yoke
neon bolt
#

nope

ashen yoke
#

actually it shouldnt matter you can just z = 0 the result vector as well

#

basically flatten both vectors on z before doing anything with them

mystic yoke
#

Can you show a screenshot of the transform when you use 0,0,1

neon bolt
#

I dont think the issue is with reading the mouse postiton as even when I spawn an object with a preset direction vector it still spawns with the wrong rotation

#

sure

mystic yoke
#

What happens if you remove the rotation code entirely

bitter hound
#

@swift falcon
if all you need from the clickedGameObject is its rigidbody, you could use
RigidBody clickedRigidBody = hit.rigidbody;
instead of the getting the gameObject, but only using the rigidbody of the gameObject.

I'm going to look a bit into your script and see what's up with it

neon bolt
#

rotation of 0

mystic yoke
#

Can you post the entire class

neon bolt
#

sure

mystic yoke
#

So I take it you're calling the second method currently?

neon bolt
#

the first

#

the line i commented out isnt meant to be. It was just to show u what happens when i removed the line that rotates the object

mystic yoke
#

Not sure it matters but is there a reason you're using quaternion instead of Quaternion

neon bolt
#

no I didn't realise I even had

mystic yoke
#

Try using Quaternion just for giggles

neon bolt
#

wow no way XD

#

that fixed it hahahaha

#

thank you so much, been stuck with this for ages

mystic yoke
#

TIL unity math structs are not compatible with unity engine structs

neon bolt
#

okay noted, thank you

stable rivet
thorn iron
#

Hey! Hi!

#

I have a really weird problem: When I'm testing my game on the editor, moving the mouse fastly around the screen makes my performance tank af

#

And, according to the profiler, it seems to be a problem with the editor?

#

And, it seems to be correct, because when building the project and testing the same thing there, nothing seems to break.

#

If anyone knows what to do about this, or needs some extra info/profiler data, idk, please, let me know, I can't work like this.

thorn iron
turbid surge
thorn iron
thorn iron
turbid surge
#

Are you running any code on mouse move?

thorn iron
bitter hound
turbid surge
#

Try turning off Pixel Perfect in the Canvas

thorn iron
bitter hound
thorn iron
bitter hound
thorn iron
swift falcon
bitter hound
#

@swift falcon

you should only check the grabbing when a mouseclick happens

#

when you do a mouseclick, you only do a Raycast once. Then, you save that raycastHit, and use it anywhere it's needed during that frame.

thorn iron
turbid surge
#

Yeah it must have been the polling rate

thorn iron
bitter hound
#

Here's what I was playing with, it ended up being quite different from yours and most likely doesn't work perfectly, but maybe you could use it for inspiration

#

@swift falcon see above

swift falcon
turbid surge
turbid surge
thorn iron
bitter hound
# swift falcon oh

basically, raycastHit is the result of a raycast. If you do the same raycast many times, you could just check the same hit property instead

turbid surge
#

discord moment

bitter hound
#

you only need to do a new raycast when the situation changes

dim spindle
#

Is my discord bugged? I see several duplicate messages

turbid surge
#

API response is slow atm

dim spindle
#

Fun

turbid surge
#

Everyone has duplicates

#

discord moment

steady moat
#

I am not sure I understand fully, but if you want the player model to be hidden when it is too close to the camera then it is a shader that you want. (99% sure of that) I am still a beginner in shader, so I can hardly help you.

However, note that doing a clone of an object is NOT a good idea. It will be hard to actually make everythings perfect. (Mainly Animation and Particule Effect). Also, you will not be able to cut the physics mesh. Instead, I suggest that you make an effect from when the player touch the portal that covers the whole player model the time it is between both world and keep the player model out of his camera. (Only the camera of the RenderTexture should see the player).

dim spindle
#

Is my discord bugged? I see several duplicate messages

quartz folio
#

Yes. Just wait for it to be over without contributing to the noise

spare island
#

Whats the best way to pause in-game audio when the game is paused? Setting the timescale to 0 does not pause sounds

turbid surge
stark jacinth
#

I need help with having my flashlight object stay in my players pov when I rotate the camera. I created an empty object then made it the parent of the flashlight and wrote some code, but it wasn’t working very well. So if anyone knows a simple way to implement this please let me know.

potent sleet
dim spindle
#

Make the player object a parent of flashlight

stark jacinth
swift falcon
#

Can anyone help explain how is this possible?

    public static Dictionary<System.Type, Singleton> Instances = new Dictionary<System.Type, Singleton>();

    private void Awake()
    {
        System.Type thisType = GetType();
        if (Instances.ContainsKey(thisType))
            Debug.Log(Instances[thisType]); // Error: Key not found
    }```

This is in a class "Singleton"
And is being run by a class "Input" which inherits from "Singleton"
#

Oh wait nvm figured it out, was missing a bang in one of the lines. Silly mistake

dim umbra
#

I need a sprite animation to play when Time.timeScale is 0, but changing the animator update mode to unscaled time doesn't seem to do anything. Anyone know what I might be doing wrong?

hexed pecan
dim umbra
#

In the aminator controller window, it has the blue bar to indicate that the animation is triggered, but it's not moving and the animation doesn't play

#

it freezes like this

#

Plus, the sprite is set to the first frame of the animation but it never actually plays

#

Changing the update mode doesn't seem to do anything at all

shell scarab
gaunt wren
shell scarab
#

Another question, one which I cannot find online. How does a value type compare when it stores a reference type? Is this something that should be avoided?

[System.Serializable]
public struct ExitDirectionPair
{
  public ExitDirection direction; // enum
  public Transform gameobject;
}
cold parrot
shell scarab
#

well how do two instances of this struct compare? Isn't it usually compared via value?

cold parrot
#

Yes, but for them to be equal, only the reference (memory address stored in the fields) has to be the same. There would be no need to actually look at the referenced object.

candid forge
#

yo, i am making a chunk loading system for a personal project, i'm currently instantiating 3 chunks in the direction i go which contain 2500 2D squares each and unload the same amount in the direction i'm not going. So instantiating 7500 times forward, destroy 7500 times backwards.

#

This creates lag spikes whenever it happens, i want to know what are ways of improving performance?

#

I have a few ideas like, putting each chunk in a coroutine or making the chunks smaller but i don't see how that is any better (since same number if instantiations need to happen

haughty ember
#

I'm having trouble working with a singleton in Unity. My PlayerHealth script can't find the gameManager object unless I use "FindObjectOfType" to declare it. However, I thought the point of singletons was that we didn't need to do this? I've seen this style of code online and it seems to work for other people, so I'm not sure what's wrong. Here's my GameManager code: ```public class GameManager : MonoBehaviour
{

public static GameManager gameManager;

//Avoids duplicate game managers
private void Awake()
{
    if (gameManager != null && gameManager != this)
    {
        Destroy(this);
    }
    else
    {
        gameManager = this;
    }
}

//Logic for when the player loses
public void GameOver()
{
    Debug.Log("Game Over");
}

}```

#

And here's the PlayerHealth code: ```public class PlayerHealth : MonoBehaviour
{
public int maxHealth;
private int health;
private GameManager gameManager;

private void Start()
{
    health = maxHealth;
}

public void TakeDamage(int damage)
{
    health -= damage;

    Debug.Log(health.ToString());

    if (health <= 0) {
        gameManager.GameOver();
    }
}

}```

knotty sun
#

and
GameManager.gameManager.GameOver();

#

should not have this
private GameManager gameManager;
in PlayerHealth

haughty ember
#

That last line fixed it, thanks :). So a few questions, what's the difference between "this" and gameObject anyways? Also, when accessing static variables, I guess I just reference the class name itself, so GameManager, and then the gameManager variable I have inside that class, right?

knotty sun
#

Also, yes, that is correct. to access public static variables it is ClassName.VariableName

#

which is why for most singletons the variable name is instance

haughty ember
#

Ah I see, that helps clear things up, thanks!

ashen yoke
#

In BIRP i have to always drop a camera with post stack for the scene to render correctly, is there a way to avoid that? Like copy the stack to SceneView camera, or some global override or anything

#

maybe i can spawn the camera with hideflags

cursive bridge
#

Can you connect a controller to your unity project?

ashen yoke
#

plug it in, it works

#

setting it up with old input is pain

#

people use either new input system or Rewired

cursive bridge
#

How I do that?

ashen yoke
#

do what

cursive bridge
#

Just connecting the control works?

ashen yoke
#

yes unity will detect the controller and you get a message in console that HID device was detected

#

difficult part is mapping the buttons

cursive bridge
#

Oof

#

Well thank ya so much mate!

ashen yoke
signal spade
#

Hello! I am a new Unity developer, though I have been a developer for a living for many years outside of gaming. I am attempting to make a large open world procedurally generated game as my first game (I know... adventurous, brave, stupid, all of the above). I am running into issues and I think I know the answer, but I wanted a sanity check to ensure I am on the right path.

Info about my process:
I'm using Unity's terrain system
I'm feeding a biome map I created in a map software via JSON to determine biome information
Logic flow:
A. Procedurally generate my starting terrain using a Biome class with primary and secondary biome height and perlin noise ranges
B. Create the next terrain using position of the terrain to the left of it, move through complex weighted chance biome rules using my imported biome map as a basis
C. Stitch the terrains together by modifying the heightmap and procedurally generate the neighbor terrain using the Biome class directives
D. Continue to loop through the terrains handling first row, first column, and surrounding terrain possibilities

My next step was to procedurally paint the textures, detailed objects, etc. as I got to that point but I am at a sang. My world is just too large. I don't want to reduce my size, I just want to come up with the solution to handle it. My world is using 300x261 terrains with a heightmap resolution of 64x64. I realize that this simply can not be done all on one screen. My intention was to save the world to a data file and load the terrains surrounding the player dynamically via individual scenes.

It is looking like my only option is to rewrite my code to save all of this data to some sort of data structure, maybe JSON, and then dynamically load it that way. I was going to have a world save file anyways. I was just trying to avoid that while developing the terrain. Does this sound like my only viable option?

knotty sun
#

my best advice as you are an experienced developer, do not use Json, use binary save

signal spade
knotty sun
#

json is absolutely crap for game dev

#

you need to develop a nice modular binary save system

signal spade
# knotty sun you need to develop a nice modular binary save system

Thank you. I was already starting down this path. I was hoping I wouldn't have to do it yet, but it seems from everything I have looked online, there is no way for me to write/read terrains within scene (even in additive scenes) without the terrains themselves being loaded and that is my problem. I was troubleshooting stitching tears in the upper quadrant of my map and resolved those, but it's just too big to keep iterating through to check to ensure the other parts of the map are okay. Data structure and dynamic loading even while in development of my terrains seem to be the way to go.

ashen yoke
#

if you are going to do this, make sure you have adamant redundancies, automatic file backups

swift falcon
#

When the player presses both movement keys simultaneously, generally what should happen in a 2D platformer?
Do they stop moving or move in the last direction pressed?

ashen yoke
#

good question i just realized i only played those with a controller and it is physically impossible to press both directions on those

#

wait no on ps one it is possible, nevermind

late talon
#

Hey, cen anyone help me whit walking sounds which detect and object and terrain surface? i cent figure it out how to make so it play only if the player moveing (cent send script bcs its to long) if u cen help please dm me, thanks

errant elbow
#
yield return new WaitForSeconds(6f);
StartCoroutine(dialogueManager1.StartDialogue(dialogues[0]));
yield return new WaitForSeconds(6f);
Destroy(square);
//
yield return new WaitForSeconds(15f);
StartCoroutine(dialogueManager2.StartDialogue(dialogues[1]));
yield return new WaitForSeconds(10f);

so after Destroy(square) i want to check if my first coroutine has done working, how can i do this?🤔

vocal root
#

is this code better than using tags to check for an item?

private void OnTriggerEnter(Collider item)
    {
        if (item.GetComponent<Consumibles>().ID == 1)
        {
            HealPlayer(1);
            Destroy(item.gameObject);
        }
    }
hexed pecan
errant elbow
#

won't i start it using yield return StartCoroutine()?

hexed pecan
#

Isn't that what I typed?

errant elbow
#

it is. I just wasn't sure if i'm not starting it again

#

using this

hexed pecan
#

Yeah it does start it

errant elbow
#

🤔

hexed pecan
#

If this doesnt work for what you need then you can use a simple bool check

errant elbow
#

yeah that's a good idea ig

#

thx!

fervent furnace
#

@vocal root theoretically compare int is much faster than string but you have to make sure the component (script) is attached to the GO collided with)
and the engine may propably optimize .comparetag and related memory operations

late talon
#
if (isOnTerrain && movingState.isWalking)
            {
                // Get the player's position on the terrain
                float normalizedX = (currentPosition.x - terrain.transform.position.x) / terrain.terrainData.size.x;
                float normalizedZ = (currentPosition.z - terrain.transform.position.z) / terrain.terrainData.size.z;
                int terrainTextureIndex = GetMainTexture(normalizedX, normalizedZ);

                // Play the walking sound based on the terrain texture
                switch (terrainTextureIndex)
                {
                    case 0:
                        audioSource.clip = grassSound;
                        break;
                    case 1:
                        audioSource.clip = PathSound;
                        break;


                }
            }
            else
            {
                // Play the walking sound based on non-terrain surface type
                RaycastHit hit;
                if (Physics.Raycast(currentPosition, Vector3.down, out hit) && movingState.isWalking)
                {
                    // Check the tag or layer of the object hit by the raycast
                    if (hit.collider.CompareTag("woodFloor") )
                    {
                        audioSource.clip = woodFloor;
                    }
                    else if (hit.collider.CompareTag("Carpet") )
                    {
                        audioSource.clip = Carpet;
                    }

                }
            }
            // Play the walking sound
            if (!audioSource.isPlaying)
            {
                audioSource.Play();
            }


#

how in this i cen make when stop walking stop play sound?

hexed pecan
cobalt gyro
#

how do i show and hide variables in the instpector depending on the enum type

hexed pecan
#

Yeah looks like that works with enums. The page has an example for it

ruby scroll
#

!code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

late talon
tiny reef
#
public class TileTypeManager : MonoBehaviour{

   public static TileType STONE, SAND;

   private void Awake() {
      STONE = gameObject.AddComponent<TileType>();
      SAND = gameObject.AddComponent<TileType>();
   }

   public class TileType : MonoBehaviour {

      private TilePool<T> pool;

      public TileType() {
         pool = gameObject.AddComponent<TilePool<T>>();
      }

   }
}

i have this TileTypeManager class which holds all my TileTypes
each TileType has a pool with a generic part
i dont want the TileType class to be generic because that just wouldnt make sense but im really struggling to think of how i should do this
any advice would be great

ruby scroll
whole steeple
#

I don't understand why my Visual Studio code doesn't recognize UnityEngine.UI and such

ruby scroll
# errant elbow

oops i misspelled that when sending the snippet but it still doesnt work

twin hull
#

@whole steeple that's actually really weird. what does the error say?

whole steeple
#

@twin hull It's in french but maybe you can make out what it is with the error codes

#

a missing reference of some sort

#

I didn't have that last time I opened my project, so I'm not sure what caused it and how to fix it

#

Not sure if it is related but Visual Studio Code gives me a prompt that the project hasn't generated the VSCode tools, and that I need to go to External Tools and set VSCode, even though it's already the case

somber nacelle
#

vs code and visual studio community are two separate programs. you have it set to use Visual Studio Community, just use that to code

whole steeple
#

Ah I wasn't aware they were different. Well I don't have VSCode, and I am using Visual Studio Community.

late talon
#
if (movingState.isWalking)
            {
                // Play the walking sound
                if (!audioSource.isPlaying)
                {
                    audioSource.Play();
                }
            }
            else
            {
                if (!audioSource.isPlaying)
                {
                    audioSource.Stop();
                }
            }

#

WHY THIS DONT STOP SOUND INSTANTLY?

ashen yoke
#

if (!audioSource.isPlaying) twice

wide terrace
#

(You only try to stop it if it's not playing)

late talon
#

oh fixed

#

just removed if after else

hexed pecan
#

Couldve just removed the ! 🤷‍♂️

whole steeple
ashen yoke
#

number 1 cause of most vs related issues

sleek bough
#

Preferences > External Tools

analog mortar
#

Wait so if I use a unity relay server to connect peer to peer, and I send a utp message through the relay server, will it end up at the other player’s client

knotty sun
analog mortar
#

So how would I be able to get a message from the client to the host client and vise versa

knotty sun
#

if you want guaranteed coms you want TCP or WebSocket protocols

analog mortar
#

k good to know

ruby scroll
knotty sun
#

UTP is fire and forget. There is absolutely no guarantee it will reach the reciever

#

nothing to do with resources. Everything to do with FindObjectsOfType. So that is where you should be looking

#

by looking in your code to where you use FindObjectsOfType

#

So the stack trace is lying?

ashen yoke
#

NetworkManagerHelper.cs:96

#

*90

rigid wraith
#

anyone know how to fix it?

ashen yoke
#

other than that typo i dont see errors

#

maybe you dont have those buttons declared as buttons

sleek bough
#

Make sure you didn't import UIToolkit buttons instead of the old UI

knotty sun
#

ah yes

            var networkManager = Object.FindObjectOfType<NetworkManager>();
ashen yoke
#

why are you downvoting it? this is literally the code in it

#

sad ending for a rather good day

swift falcon
#

!code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

swift falcon
#

Hello, I'm building a combat system for a game that I'm making and I'm stuck on an edge case for my code. Essentially, my game is represented through 2D squares which are individual units. Melee units have an invisible square box in front of them, that's supposed to detect other unit's hitboxes, and begins combat when this "melee engagement" trigger is activated. However, if 2 melee units attack each other frontally, then both OnTriggerEnter method will run, causing a lot of issues as the combat method involves moving the attacking unit relative to the defending unit, and executing this code at the same time causes the units to bug out.

Below is the method for my OnTriggerEnter, which is attached to my "melee engagment" trigger that detects when other units enter its hitbox.

private void OnTriggerEnter2D(Collider2D other)
    {
        // If the other collider is a unit hitbox, the script isn't detecting a collision with its own unit, and the unit isn't attacking, initiate combat.
        if (other.gameObject.CompareTag("Unit Hitbox") && other.gameObject != _parentUnit && !_parentCombatScript.isAttacking)
        {
            _parentCombatScript.InitiateCombat(other.gameObject);
        }
    }
#

Below is my InitateCombat method

public void InitiateCombat(GameObject enemyHitBox)
    { 
        var enemyGameObject = enemyHitBox.GetComponent<MeleeHitBoxDetectorController>().unit;
        var enemyMeleeHitBoxDetectorScript = enemyHitBox.GetComponent<MeleeHitBoxDetectorController>();
        var side = enemyHitBox.GetComponent<MeleeHitBoxDetectorController>().side;

        // Set attacking and defending flags and get a reference to the attacking unit.
        isAttacking = true;

        // Set both units to engaged.
        unitScript.SetIsEngaged(true);
        enemyGameObject.GetComponent<Unit>().SetIsEngaged(true);

        // Disable this unit's collision with the other gameobject
        Physics2D.IgnoreCollision(GetComponent<Collider2D>(), enemyGameObject.GetComponent<Collider2D>());

        // Disable the other unit's collision with this gameobject.
        Physics2D.IgnoreCollision(enemyGameObject.GetComponent<Collider2D>(), GetComponent<Collider2D>());

        // Move this unit according to the other unit's position.
        transform.position = enemyMeleeHitBoxDetectorScript.GetPositionForAttackingUnit(gameObject);

        // Rotate the unit to face the enemy unit.
        transform.rotation = enemyMeleeHitBoxDetectorScript.GetRotationForAttackingUnit(gameObject);

        // Start the combat coroutine.
        StartCoroutine(CombatCoroutine(enemyGameObject, side));
    }
heady iris
#

can't you just ignore the other unit if you're being attacked already

swift falcon
#

If an attacker attacks a unit from the side, the defending unit won't attack that unit (as it should), but the issue is when 2 units go head on

heady iris
#

unit A overlaps first, so now unit A is attacking unit B
unit B overlaps, but it's being attacked, so it ignores the overlap

#

unless i'm missing something here?

turbid surge
#

The question is what do you want them to do when they attack each other head on

#

Otherwise how do we know how to "fix" it?

exotic aspen
#

Howdy folks. I would like to plan my Unity 2D game to support extensible modding in the future, but am somewhat lost on how one would approach this. I've successfully exposed stats and map design via JSON files that can be edited or replaced. But do any tutorials or how-to's exist for dynamically loading sprites, animations and Prefab type stuff? Given how proprietary/unique these objects are, I can't quite get how to approach adding extensibility for new types of things. I am fine if this effort would be aided through the use of 3rd party APIs or purchased stuff on the Asset Store. And I realize anything would require heavy customization. Just trying to get my arms around it is all 🙂

turbid surge
swift falcon
#

This video kinda shows what the issue is. If you look at the top left corner, the red bar is indicating that both units are taking damage. However, you also notice that weird jump both units do when they go head on

turbid surge
swift falcon
#

I just want to make clear that both of those units are melee units, so they both have that invisible melee engagement trigger, and I believe that both are calling the same OnTriggerEnter methods when they go head on

turbid surge
#

ScriptableObjects can help with that so that you can just load in custom SOs to an existing object

exotic aspen
turbid surge
exotic aspen
#

I see, so basically make a new set of objects/scripts that just look in a given place and generate based on what is provided?

turbid surge
#

Yeah, really depends on what you want modded, and how you want to distribute the content

swift falcon
turbid surge
swift falcon
swift falcon
#
public Vector3 GetPositionForAttackingUnit(GameObject attackingUnit)
    {
        // Get the width and length of the attacking unit.
        float attackingUnitWidth = attackingUnit.GetComponent<SpriteRenderer>().bounds.size.x;
        float attackingUnitLength = attackingUnit.GetComponent<SpriteRenderer>().bounds.size.y;

        return side switch
        {
            Side.Front => new(unit.transform.position.x, unit.transform.position.y + attackingUnitLength, 0.0f),
            Side.Left => new(unit.transform.position.x - attackingUnitWidth, unit.transform.position.y, 0.0f),
            Side.Right => new(unit.transform.position.x + attackingUnitWidth, unit.transform.position.y, 0.0f),
            Side.Back => new(unit.transform.position.x, unit.transform.position.y - attackingUnitLength, 0.0f),
            _ => throw new ArgumentOutOfRangeException()
        };
    }
#

So this code is attached to each side of the hitbox for the unit. The unit hitbox isn't the collider for the square, but rather a tiny rectangle representing which side of the unit it's attacking from

turbid surge
#

Looks to me almost as if the units are moving into each other and then triggering a side hitbox and attacking from the side

exotic aspen
# turbid surge Yeah, really depends on what you want modded, and how you want to distribute the...

As an example, my game has Units of various types. I've defined them each with a Prefab consisting of sprites/animations, extensive set of stat properties, an AI script, sounds and so on. I've already exposed the stats, sounds and some knobs for folks to replace/change. But adding a new one entirely seems tricky. How does one even dynamically build up animations, keyframes and all of that from files/json that players modify in a folder?

turbid surge
swift falcon
#

Yes ur correct I just checked

turbid surge
#

This will allow unity to do most of the heavy lifting of importing animations and having them in the "unity" format, and then you can simply package this into an Addressable or something and use it

swift falcon
#

The top unit is registered as attacking frontally, but the bottom unit is registered as attacking from the left side

turbid surge
swift falcon
#

I've created this method, which is just a stripped down version of the previous InitiateCombat method I posted earlier

public void InitiateCombatWithoutMovement(GameObject enemyHitBox)
    {
        var enemyGameObject = enemyHitBox.GetComponent<MeleeHitBoxDetectorController>().unit;
        var side = enemyHitBox.GetComponent<MeleeHitBoxDetectorController>().side;

        // Set attacking and defending flags and get a reference to the attacking unit.
        isAttacking = true;

        // Set both units to engaged.
        unitScript.SetIsEngaged(true);
        enemyGameObject.GetComponent<Unit>().SetIsEngaged(true);

        // Disable this unit's collision with the other gameobject
        Physics2D.IgnoreCollision(GetComponent<Collider2D>(), enemyGameObject.GetComponent<Collider2D>());

        // Disable the other unit's collision with this gameobject.
        Physics2D.IgnoreCollision(enemyGameObject.GetComponent<Collider2D>(), GetComponent<Collider2D>());

        // Start the combat coroutine.
        StartCoroutine(CombatCoroutine(enemyGameObject, side)); 
    }
turbid surge
#
///Pseudocode
if(!_attacked)
{
  MoveToUnitToAttack();
}

swift falcon
#

ooooo

heady iris
#

as I suggested earier, just break the cycle :p

turbid surge
#

Yup

heady iris
#

now, if you're okay with making a circle of attacking units

#

you'd need to be more specific: if I'm being attacked by Foo, don't attack Foo

turbid surge
#

Or expose isAttacking as public and check using the reference to the unit to attack if it is attacking and if so don't move

#

You've got a bit of a code smell here too

swift falcon
#

Okay so this is what Ive changed

#

I've have 3 main properties in my combat script that controls head-on attacks, a public isAttacking bool, a public isDefending bool, and a private reference to the defendingUnit.

I've edited the InitiateCombat method to include the if statements.

public void InitiateCombat(GameObject enemyHitBox)
    {
        if (isAttacking)
        {
            Debug.Log($"{gameObject.name} is already attacking {enemyHitBox.GetComponent<MeleeHitBoxDetectorController>().unit.gameObject.name}");
            return;
        }
        if (isDefending)
        {
            Debug.Log($"{gameObject.name} is already defending, will attack {enemyHitBox.GetComponent<MeleeHitBoxDetectorController>().unit.gameObject.name} still.");
            InitiateCombatWithoutMovement(enemyHitBox);
            return;
        }

        var enemyGameObject = enemyHitBox.GetComponent<MeleeHitBoxDetectorController>().unit;
        var enemyCombatScript = enemyGameObject.GetComponent<Combat>();
        var enemyMeleeHitBoxDetectorScript = enemyHitBox.GetComponent<MeleeHitBoxDetectorController>();
        var side = enemyHitBox.GetComponent<MeleeHitBoxDetectorController>().side;

        // Set attacking and defending flags
        isAttacking = true;
        enemyCombatScript.isDefending = true;
        _defendingUnitReference = enemyGameObject;
...
#

The InitateCombatWithoutMovement works and is functionally similar to the InitiateCombat method, expect it doesn't move nor rotate the unit that script's attached to.

I've also changed my CombatCoroutine to constantly update the flags of the attacker and defender

public IEnumerator CombatCoroutine(GameObject enemyGameObject, Side attackingSide)
    {
        var enemyUnitScript = enemyGameObject.GetComponent<Unit>();
        var enemyCombatScript = enemyGameObject.GetComponent<Combat>();
        float dmgMultiplier = attackingSide switch
        {
            // Front is no multiplier, sides are 10% buff, back is 25% buff
            Side.Front => 1.0f,
            Side.Left => 2.0f,
            Side.Right => 2.0f,
            Side.Back => 4.0f,
            _ => throw new ArgumentOutOfRangeException()
        };
        float dmgDealt = unitScript.dmg * dmgMultiplier;

        while (!enemyGameObject.IsDestroyed())
        {
            isAttacking = true;
            enemyCombatScript.isDefending = true;
            
            enemyUnitScript.dmgReceived += dmgDealt;
            
            if (enemyUnitScript.dmgReceived >= enemyUnitScript.hp)
            {
                float excessDmg = enemyUnitScript.dmgReceived - enemyUnitScript.hp;

                enemyUnitScript.dmgReceived = excessDmg;

                enemyUnitScript.manpower--;

                if (enemyUnitScript.manpower <= 0)
                {
                    Destroy(enemyGameObject);
                    break;
                }
            }

            yield return new WaitForSeconds(1.0f);
        }

        _defendingUnitReference = null;
        isAttacking = false;
        unitScript.SetIsEngaged(false);
    }
#

And finally, the script has a OnDestroy event, which uses the defending unit reference to set their isDefending bool to false if the attached gameObject gets destroyed

public void OnDestroy()
    {
        if (_defendingUnitReference != null)
        {
            _defendingUnitReference.GetComponent<Combat>().isDefending = false;
        }
    }
turbid surge
#

Ok, does it work?

swift falcon
#

The issue with this code though is that it only works around 50% of the time. Because these methods run near-simultaneously, sometimes both units gets their isDefending bool set to true and both begin attacking without movement

#

So yea this code still bugged

#

OKay nvm I figured it out

#

So basically, I changed one line in the InitiateCombatWithoutMovement method so that it doesn't set the other gameobject as defending

 public void InitiateCombatWithoutMovement(GameObject enemyHitBox)
    {
        var enemyGameObject = enemyHitBox.GetComponent<MeleeHitBoxDetectorController>().unit;
        var enemyCombatScript = enemyGameObject.GetComponent<Combat>();
        var side = enemyHitBox.GetComponent<MeleeHitBoxDetectorController>().side;

        // Set attacking and defending flags
        isAttacking = true;
        _defendingUnitReference = enemyGameObject;
#

But that still only fixes 1 edge case. If a unit attacks head-on to a unit that's already getting attacked by someone else, this code works. However, if both units are not being attacked, this code will still bug out.

#

Yea from what I can see the top unit is attacking the unit fine, but the bottom unit somehow registers that it's attacking the unit from the left

potent sleet
#

Any ideas how I would approach lining up one these quad through its center to the blue dots, when the wheel close to stopping speed?

dawn nebula
#

Is there a way to define how a certain class serializes in Unity's inspector in a separate class?

#

So I don't need to add a bunch of attributes to the original class everywhere.

#

Or if I don't have the ability to edit that class.

turbid surge
turbid surge
#
var _angle = 360 / spinnerSides;
var _angleMidpoint = _angle + (_angle / 2);
transform.rotation = Quaternion.Euler(RoundedToNearestAngleMidpoint(transform.rotation.x), transform.rotation.y, transform.rotation.z);

Some pretty bad pseudocode but I hope you get the idea

potent sleet
#

I can show you my current very basic ass code if you want

#
  if (canSlowDown && wheelSpeed > 0)
        {
            finished = false;
                wheelSpeed -= Time.deltaTime * speedDepleteRatio;
        }

        wheel.Rotate(wheelSpeed, 0, 0);
turbid surge
#

Yeah sorry just had to brush teeth

hybrid harness
#

Having trouble with this block of code, specifically with the while statement
seems to be 'decaying' faster than its supposed to.
the goal of this code is to set the bpmCurr value to value, and keep it there for length seconds, then set bpmCurr to decayValue over the course of decay seconds

turbid surge
#
private float RoundedToNearestAngleMidpoint(float _currentRot) // It was a function just for less code
{
  _fraction = _currentRot / _angle;
  return (Mathf.Round(_fraction) * _angle) + (_angle/2);
}
#

Something like this @potent sleet

#

I think the diagram might not help

wide terrace
# hybrid harness Having trouble with this block of code, specifically with the while statement se...

Using the current value of bpmCurr as the first argument of the lerp will have a couple strange side-effects. The Lerp will slow down towards the end, and since it's bpmSim cast to an int, it means that the lerp is always starting from the last result rounded down - which in this case means that the lerp is accelerated (a return value from Lerp of 5.9 means the Lerp in the next iteration will use 5 as it's starting value.

I think just using value as your first Lerp argument would solve the issue. But I might think to write it all as such:

float endTime = Time.time + decay;

while ( bpmCurr != decayValue ) {
  yield return new WaitForEndOfFrame();
  bpmCurr = (int)Mathf.Lerp( value, decayValue, (endTime - Time.time) / decay );
}
lofty moat
#

i joined this server for literally 5 minutes the only thing i want is how the absolute hell did this guy in a tutorial get the "CameraHolder" thing and how do i get it ive been looking for idk how long please im begging anyone how do i get this

wide terrace
wide terrace
potent sleet
quick ridge
#

Hoping this is the right place to put this... But I've recently switched PC and moved my project into a new directory. Everything runs fine, except in visual studio it doesn't recognise the UnityEngine.Rendering.Universal namespace or TMPro. I still have the packages imported, I've tried uninstalling and reinstalling them without success. The project still runs leaving me to believe it's a visual code issue but I haven't found anything online to fix it. Any ideas?

heady iris
#

have you tried regenerating the external project files

#

Preferences (not Project Settings) -> External Tools

quick ridge
#

Yes, I've tried that. Didn't make a difference :/

spare island
#
        var audioSources = _audioSources;
        foreach (var audioSource in audioSources)
        {
            if (audioSource.gameObject.CompareTag("ExcludeFromPause"))
                _audioSources.Remove(audioSource);
        }

How can I do this without modifying the collection? I'm a bit rusty
I thought using a temporary variable would work but it still throws an exception for modifying the collection

heady iris
#

audioSources and _audioSources are the same thing

#

they reference the same object

#

one option is to copy the collection

#

new List<AudioSource>(_audioSources), for example

spare island
heady iris
#

well, List<T> is a reference type

#

so any variable of type List<T> is a reference, yes

#

not to be confused with being a ref

#

😵‍💫

spare island
#
        var audioSources = new List<AudioSource>(_audioSources);
        foreach (var audioSource in audioSources)
        {
            if (audioSource.gameObject.CompareTag("ExcludeFromPause"))
                _audioSources.Remove(audioSource);
        }

so like this

heady iris
#

That'd work, yeah. A bit clunky, though.

spare island
heady iris
#

one option: use LINQ

_audioSources = _audioSources.Where(x => !x.gameObject.CompareTag("ExcludeFromPause")).ToList();
#

if you really want to be efficient about it, I guess I'd just write a loop that checks each index and removes the item at that index if needed

#

(and that decrements the index if that happens)

spare island
#

i've already tested this script with over 4096 audiosources, and at that point the audiosources themselves cause more lag than this script ever could

#

the worst i could get (before the game was unplayable) was 10ms

wide terrace
# potent sleet can you explain a little how would I approach that ? I'm actually horrible with ...

Well you know I'm a general noob overall, so this may not work as it does in my head 😁

But when the wheel's speed is "slow enough," I would think to start casting rays from a little in front of the wheel - from right in the center of where you'd like the face to be oriented - towards the wheel, and use the hit normal from there. For rhetoric I'll just assume the desired orientation that a face should stop at is just like Vector3.forward

If the hit normal is angled downwards on the global y axis, it would mean that the face currently in that location has already passed Vector3.forward, and you might start to dampen and reverse the wheel's rotation so it sort of smoothly comes to a rest on that face. Or maybe prevent the wheel's rotation from stopping so it moves on to the next face.

If the hit normal is angled upwards on the y axis, then it's not yet oriented straight forward, and you could do something like

var degreesOffset = Vector3.Angle(hit.normal, Vector.forward);
wheelSpeed *= degreesOffset / angleOfFacesToOneAnother; // Where the latter is the acute angle between two adjacent faces' planes... probably like 18 in the case of 20 faces?

so that the speed will slow down the closer the face is to Vector3.forward, scaling down from whatever it's original speed was beforehand... When hit.normal is aligned with Vector3.forward wheelSpeed will be scaled to 0...

This isn't like super thought out or probably all that would be required, but I hope it helps sort of clear things up a bit?

Edit: though solving it with math instead of physics might be a lot better, especially if it needs to be deterministic I suppose 👀

dusk apex
spare island
#

the solution i have now works but ill keep it in mind

dusk apex
#

You've cloned the list and iterated the clone to remove elements from the original. Memory will eventually have to be freed by the garbage collector.

dusk apex
#

Just saying

spare island
#

i already knew that it makes a lotta garbage i even specifically put a comment above the method mentioning that

#

but ehhhhhh garbage smarbage

#

anyway is there a way built into unity's UI for me to do something like, if i press the escape (back) button in a menu it presses the back button currently on screen

#

i've had a lot of trouble ever trying to get the 'navigation' element of UI to work correctly and im not sure if i should be doing this stuff through code or inside of unity

dusk apex
#

Have them both call the same function rather than a key trigger a ui button.

leaden ice
#

ICancelHandler

#

Also the OnCancel thing in EventTrigger

#

The catch is it only triggers on the currently selected object

potent sleet
spare island
#

im considering just manually coding this tbh

#

because i have the problem of a menu with submenus, i dont want pressing escape to close all of the menus at the same time time

#

i want it to just go back one menu

#

and the whole "selected object" thing does not really make sense on keyboard and mouse

potent sleet
spare island
wide terrace
potent sleet
#

ty

spare island
#

idk what to do here, i thought it would be pretty simple to just have a linear way to progress through the menu with the keyboard

#

but its impossible to even select a button without clicking it

heady iris
#

and you've got a gacha

dim umbra
#

Is there any way to make buttons that are being pressed carry over between scenes?

mortal tusk
#

Tho something tells me that's not exactly what you're looking for based off of your question

#

Some more info would probably help

dim umbra
#

It could work, but I don't understand why "GetButton" doesn't work after loading a scene. Isn't it just checking if that button is held down at that frame?

#

If you started pressing the run button before the scene change, you need to re press it to be able to run when the scene loads

heady iris
#

GetButtonDown is only true for one frame.

#

you probably just want GetButton

dim umbra
#

oh sry not what i meant

#

yea I'm using that

mortal tusk
heady iris
#

i'm not sure how they behave across a scene transition

dim umbra
#

I meant to say GetButton

mortal tusk
haughty ember
#

Having some trouble setting up a goomba style enemy in a 2D game. First, I have a Damage script and a Health script for both the enemy and the player, one for them to do damage to other entities, and the other to track health. My issue is, when my player jumps on the enemy to kill it, it still takes damage, and actually takes 3x as much damage as it should! Here's my enemy damage script: ```public class EnemyDamage : MonoBehaviour
{

public int damage;

//Deal damage to the player
private void OnTriggerEnter2D(Collider2D collision)
{
    PlayerHealth player = collision.GetComponent<PlayerHealth>();

    if (player != null && transform.position.y <= collision.transform.position.y)
    {
        player.TakeDamage(damage);
    }
}

}```

#

And my player damage script: public class PlayerDamage : MonoBehaviour

{
    private void OnCollisionEnter2D(Collision2D collision)
    {
        // Check if the collision is with an enemy
        EnemyHealth enemy = collision.collider.GetComponent<EnemyHealth>();
        if (enemy != null)
        {
            // Check if the collision is from above
            if (transform.position.y > collision.transform.position.y)
            {
                // Collision is from above
                enemy.TakeDamage();
            }
        }
    }
}```
fickle lichen
#

Hey I have a question regarding pooling design pattern: Is it better to use Stack instead of List to store reusable objects? Or it doesn't matter?

heady iris
#

Stack is probably a little easier to work with

#

since you just use Push and Pop

#

doesn't matter otherwise

fickle lichen
heady iris
#

no idea. probably doesn't matter

haughty ember
#

Ah never mind, turns out I fixed it, simply had to switch a less than to a greater than lol. Is this good practice though? Damage and Health in their own scripts?

fickle lichen
lean sail
#

itll just be more annoying when u need to access like the 5th element, have to pop and re-add everything

fickle lichen
#

It can be either first or last or from the middle, doesn't matter which one.

lean sail
#

well u need the elements to not be in use

fickle lichen
#

So if all elements are in use that array is empty

lean sail
#

what are u pooling that u need to remove the elements from the list? From the pooling examples ive seen its always just disabling/enabling the object and creating more if no objects are enabled

heady iris
#

well, you need to keep track of the objects you have available..

fickle lichen
lean sail
#

is it bad to keep track of them by disabling which ones are inactive/available to be spawned? For the example of bullets, I dont see a reason to add them to a new list, because if you dont disable it then it will just be rolling around in the world

fickle lichen
heady iris
#

but surely you must keep a list of the objects that are in the pool

#

maybe there's a miscommunication here

#

you're not advocating for not tracking the objects at all, right

lean sail
#

i know they must be kept in 1 list, i am asking about storing it in 2 lists: 1 for active and 1 for inactive. Because i thought thats what "?" was asking for

#

by saying removing them from the list

heady iris
#

gotcha

#

I would have a list that holds pooled (but unused) objects

#

and then just not have a list of in-use objects at all

#

those objects must be returned to the pool by some other game system

#

if you have a list of every object (both waiting in the pool and active in the game), then you'd need to scan through it to find an unused object every time the game asks for an object

lean sail
#

i see what you mean, so for example a bullet would add itself back to the pool once its hit something?

heady iris
#

right

#

the pooling system shouldn't need to constantly poke all of its active objects to see if they need to be returned to the pool

lean sail
#

guess that makes more sense than looping through the entire list checking if its active lol, i saw a tutorial that did it like this and didnt think otherwise

heady iris
#

imagine if the librarian came to your door every hour to ask if you're done reading :p

fickle lichen
#

While it's easy to keep track of pooled objects in a list, it's not easy to keep track of messages by people not mentioning me on Discord

fickle lichen
#

More pooled objects = more frame rate issues, so this approach is good if there are a few pooled objects

#

Do I sound nerdy? Or something? catStare

heady iris
#

O(no)

fickle lichen
spark sandal
#

Don't mean to jump over anyone else's question, but does anyone know if there is there a way to run some code slightly before the unity editor play button press kicks in? In a nut shell, my game has a lot of additively loaded scenes, and if one of the secondary scenes is loaded when i hit play (which i do by accident 50% of the time) the game breaks. I just want to check that these extra scenes aren't loaded, and exit play if so.

heady iris
#

you can choose from a few different times

#

I'm not sure when, exactly, would be the right moment for you

fickle lichen
spark sandal
#

maybe i can make my own play button

heady iris
heady iris
#

I also ran headlong into that when trying to set up some static stuff before an Awake method ran

#

the default is AfterSceneLoad, I believe

spark sandal
#

so maybe implement this to unload unwanted scenes when playmode changes?

fickle lichen
quartz folio
#

It's called many times, just filter out the one you want, which is presumably the one before the editor even enters play mode

spark sandal
heady iris
#

ooh, that looks good.

potent sleet
heady iris
#

🤨

potent sleet
heady iris
#

true

spark sandal
#

responding to the playmodestatechange is almost perfect, except i can't figure out how to unload a scene but keep it in my hierarchy. it just totally blasts it away

shell scarab
#
Dictionary<TilemapID, Tilemap> savedTilemaps = new();
``````cs
foreach (KeyValuePair<string, Tilemap> b in savedTilemaps)
{
Debug.Log(b.Key);
}

I don't understand why I'm getting the error. It happens when I try to get it like this in a property:

    public BoundsInt mapBounds
    {
        get
        {
            if (!baked)
            {
                for (int i = 0; i < tilemaps.Length; i++)
                    if (tilemaps[i].id == TilemapID.BASE) // id is a string in a struct, contains a tilemap and a string. This part works fine, so please ignore.
                        return tilemaps[i].tilemap.cellBounds;
            }
            else if (savedTilemaps[TilemapID.BASE] != null) // when baked is true, it won't work. I don't know why. As you can see above/below, it is logging that there is a key "base" in the dictionary.
            {
                return savedTilemaps[TilemapID.BASE].cellBounds; // this is converted from TryGetValue, which is why it looks a little weird.
            }

            return default;
        }
    }
heady iris
#

the error happens before the keys get logged

#

you're probably doing things in the wrong order

#

i.e. trying to use the contents of the dictionary before adding them

shell scarab
#

here's a better screenshot then:

#

it is clear in this screenshot that it is not the order.

heady iris
#

do you have multiple objects with this component on them?

shell scarab
#

no

near rover
#

Weird problem I'm having: upon instantiating a rigged mesh, sometimes the bones of the skeleton are parented out of order.

Is there a way, maybe through an array, to order all the bones and then have them check if they're in the correct order? I know it'd be a little intensive, but I wouldn't need to run it 100% of the time.

Or maybe "copy the parenting info of this prefab"?

heady iris
#

i would not expect the transforms to get rearranged

#

can you show a screenshot of the hierarchy that shows the difference?

heady iris
#

I see you have a property drawer

shell scarab
#

why would the dictionary for the same object return empty then?

heady iris
#

i don't know. show your code.

#

all of your code, not just some of it

shell scarab
heady iris
#

The entire script.

#

that should be self-evident.

#

it would be nonsensical to ask you to send me every single script in your project.

shell scarab
#

no, because then there's things in the script that people ask to see because it's not built into unity, like another class, and it just spirals.

heady iris
#

yes, which I would ask for

#

don't be obtuse

shell scarab
#

that is the entire script.

heady iris
#

you have sent three blocks of code

shell scarab
#

foreach is in an update method, and there's an array of tilemaps (the struct) and a bool for baked. That's it. That's the only part I didn't include.

#

I gave up on this way anyways, I got it working now.

swift falcon
#

Does active threads( new Thread()) gets destroyed when switching scenes?

hollow isle
#

https://hatebin.com/rbnyoqfoyv How can I choose ONLY the selected variables from my enemyType enum at random and then Instantiate them in SpawnEnemy() without having to copy it over and over again for each enemy type. I was thinking I could pass the prefab's name into the function or something but I couldn't figure out how to do that.

mossy snow
#

your design of Spawner sucks. Delete enemyType. Delete all prefabs. Add serialized array that contains prefabs the spawner will create

lean sail
#

well dont delete the actual prefabs awkwardsweat just the hardcoded game object references

mossy snow
#

yeah I mean the fields :)

loud wharf
#

Why is it an enum? UnityChanThink

hollow isle
sleek bough
loud wharf
#

Wew, people normally learn arrays before enums.

hollow isle
#

Yeah I only learned about enums because someone here helped me fix a problem by using them and that's basically the only thing of that type I know lol.

sleek bough
#

enum is not the problem, you are overriding their values to 1,2,4... which are used to keep data compact, for networking for example. Unneeded otherwise.

loud wharf
#

Isn't bitwise necessary for flags?

hollow isle
#

I also did that because I asked someone where how I could allow you to select muliple types and they told me to do that

hollow isle
sleek bough
#

so to get number 4 you need to shift it 3? times from zero. I rarely use it so might be wrong on how exactly

loud wharf
#

You mean 1<<n?

#

That stuff?

sleek bough
#

So to pull value from this enum you need to generate random 1-4 integer which will be used as how many positions to shift so you can access resulting value in enum

hollow isle
sleek bough
#

just remove value overrides and get random number as their default index

loud wharf
#

Given the purpose.

#

Then use Random.Range(0, Array.Length) to randomise which enemy spawns.

hollow isle
#

I would need two arrays as far as I know

#

because I need to select which ones the spawner uses

loud wharf
#

And?

hollow isle
#

then another array for only the ones I actually chose and that array would be the length of however many I chose to random numbers would work

#

nah I'm just typing my thoughts just in case im wrong

loud wharf
#

I'm not sure if the first array there is even necessary.

#

Is it used for a monobehaviour?

hollow isle
#

the script?

#

yeah it's monobehaviour

loud wharf
#

Yeah I don't think the first array is necessary at all.
Since you can make a non static variable and set the values.

narrow wolf
#

Hmm, what's cookin?

#

No hmm emote in this server sadge

loud wharf
#

Since I'm not sure what you can do with it, I suggest you learn Scriptable Objects too.

hollow isle
#

If i used random.range with the array that I select from in the editor the array could be 5 long, but I only choose two. It would make a number between 1 and 5 which could be any of them

loud wharf
hollow isle
narrow wolf
#

That's way too deep thinking.. I wanted casual one lmao

loud wharf
#

Ok.

loud wharf
#

Or I guess it's meant to dictate what you can use? UnityChanThink

#

The first array doesn't sound like it's going to be used.

narrow wolf
#

Uhh man... My code is such a mess I want to wipe out all 400 lines and rewrite again UnityChanHelp

hollow isle
#

then I can use random.range on that second array

#

I mean that's how It makes sense in my head

hollow isle
#

If I use random.range on the first array (which we'll say is 5 elements), it'll give me a number between 1 and 5

#

this wouldn't work if I only selected two things

narrow wolf
#

10 abilities added in a single class and many of them interfering with each other.

#

Everything is glued together using copium. If I find a bug and have to change one thing then the entire functionality breaks

loud wharf
#

J

#

Ok it's sending finally.

hollow isle
#

im fairly sure? it's just going to store prefabs. or gameobjects or whatever

lean sail
#

Is this still about spawning a random npc from a list?

hollow isle
#

yeah

lean sail
#

have u made that array or list yet?

loud wharf
#

Yeah unrelated but learn Scriptable Objects when you can, that helps you cut down on prefabs.

hollow isle
loud wharf
lean sail
loud wharf
hollow isle
#

I haven't opened unity in a second so I really haven't made the arrays yet

#

im playing games with friends and I don't want to just not respond to you guys

lean sail
narrow wolf
hollow isle
#

I have one script called "Enemy" that I put on each prefab. Each enemy prefab is a little different and has a different model and im just spawning those prefabs

lean sail
#

SO wont help u then if the model is different

hollow isle
#

yeah different enemies different models

lean sail
#

some data can be stored in an SO, but really i wouldnt worry about that rn

#

all u need is an array/list of game object, use [SerializeField] then drag them in through the inspector. Randomly select an int (0, number of prefabs) and spawn that

loud wharf
#

His question extends to which of those elements in the array can be used.

lean sail
#

dont store the ones u cant use..

loud wharf
#

Yeah that's literally what I'm thinking.

#

But eh, I already asked that.

hollow isle
#

once again im still confused. If you have a list of 5 prefabs, and then only select two out of that list, using random.range on that list will provide a number between 1 and 5, not between the two that you select in the editor

loud wharf
#

Anyways.
Make a new class that doesn't inherit to monobehaviour.
Add [Serializable] on top of it.

The only contents should be the Enemy prefab.
And a Boolean on_use or something.

Make an array out of that class. That should do your first array.

lean sail
hollow isle
#

I think my explanation isn't coming out right

lean sail
#

explain what u want to happen in your game, not in code

loud wharf
#

For the second array which is the enemy prefab add [HideInInspector] leave it be.

On Start of the Spawner script, make an List<Enemy or smth>

Foreach( element in first array) add
If element.on_use == true Lists.Add(element.enemy)

hollow isle
#

I want one spawner to be able to spawn for instance, a shotgunner, or a machinegunner.

Then, a different spawner could be spawning a flying orb and a tanak

lean sail
#

Ok so only store the shotgunner and machinegunner on spawner 1.

#

you dont need 2 arrays

hollow isle
#

now I think you're misunderstanding me

#

how do you think it would work with only one array

lean sail
#

Give me like 2 seconds to make an example on my project

#

2 arrays wont help u

loud wharf
#

Each game object on game menu is an instance.

lean sail
#

if u need a 3rd spawner, are u going to make a 3rd array?

hollow isle
#

no that's not what im saying

loud wharf
#

Each values in that instance can be different.

hollow isle
#

not at all

#

2 arrays, any number of spawners

#

each spawner just has the same script attached, which happens to have 2 arrays in it

lean sail
#

u havent even tried this with 1 array, why do u have 2

hollow isle
#

because two is the only way it works in my head

loud wharf
#

I'm more concerned with how little you know scripting.

#

Not involving Unity stuff.

hollow isle
#

I learned C# for unity so like that might be why

#

I learned C# through unity

loud wharf
#

Yeah learn just the C# first.

lean sail
hollow isle
#

why wouldn't two arrays work though???

#

one for the initial selection, then one that random.range will use

loud wharf
hollow isle
#

even IF you select only two out of the array, Random.Range will still return something between 1 and the list length, not just a number based on only how many you selected

#

that's why you make the second array which is only the ones you've selected out of the first array so random.range will get only those

lean sail
loud wharf
lean sail
#

and why have 2 arrays if u dont plan to use the first

hollow isle
#

I was thinking it would work like a drop-down list like an enum, not like that where you just add the ones you want

lean sail
#

Thats a bad idea really for this

hollow isle
#

I didn't know that you could just add only the ones you want to the array like that in the editor

hollow isle
#

before you sent that Image I was still under the assumption that arrays showed up in the editor like an enum

loud wharf
#

Well, unity can display any field on editor except delegates. Just a rule of thumb I guess.

lean sail
#

ill simplify a bit: both objects, spawner1 and 2, are unique so they both have their own array stored. The arrays are not related to each other and know nothing about each other
When you used enums, you were providing it the same enum so it will always have every single option

hollow isle
lean sail
#

i can choose the same thing here

#

i just drag in every option i want

hollow isle
#

yes I know that now I'm saying that you're right and I just wasn't sure of how exactly an array worked

lean sail
#

there were more problems with your enum other than that as well. It just doesnt make sense to use especially with it each enum value being 2^n. You would be limited to 32 things to spawn max

#

alongside just that your enum would then have to look up the prefab

#

in this case, the prefab is directly accessed

loud wharf
hollow isle
lean sail
lean sail
#

i didnt write anything to actually spawn the objects, just showed how this works in inspector

hollow isle
#

oh speaking of that I should probably change a lot of my public variables to privates with [SerializeField]

lean sail
#

why an array

hollow isle
#

wait so is that not an array?

loud wharf
#

Why a list? I personally just use array if I know I won't add or remove another element to it.

lean sail
#

its a list, it will be almost identical. The only difference is u dont have to worry about resizing a list

hollow isle
#

I was calling it an array this whole time I don't even know where I am im lost lol

lean sail
lean sail
loud wharf
hollow isle
#

Every time I come to this server I only understand like every third word said and it never gets better 😭

loud wharf
#

Yeah demonstration via code block would be good.

lean sail
#

well u havent used arrays or lists yet, itll be understandable when u experiment

loud wharf
#

But I'm nn phone.

#

Might as well show the necessities like getting the index or how to add an element to a list.

#

Also Arrays and List starts from 0, not 1.

lean sail
#

thats how u learn to get familiar with new things

loud wharf
hollow isle
#

I did so much searching on how to do it with enums before asking here because I didn't really know that lists could do it a million times better

lean sail
#

or when things are just really obscure and you have to hope someone had the same issue as u lol

loud wharf
#

Wew

#

I asked for and deep copy code that works with unity objects.
I didn't get my answer tho.
I at least found some guy that made a recursive memberwise clone and I just yoinked that stuff. UnityChanThumbsUp

lean sail
#

honestly dont know why u would ever need a deep copy

swift falcon
#

hello everyone... I am getting a "UnauthorizedAccessException" error:

//string var has its value now
File.WriteAllText(Application.absoluteURL + "/textFile.txt", stringVar);

"Access to the path "C:\textFile.txt" is denied."
as you can see I used absoluteURL... i dont know what's the cause of this

lean sail
#

You dont need to specify such a url, also you shouldnt be writing directly to the C drive

swift falcon
mellow sigil
#

absoluteURL is not for that purpose. You're thinking of persistentDataPath

lean sail
#

Default company folder 😎

swift falcon
#

😂 i can't believe i messed up between those two 💀

#

thank you both

hollow pelican
#

!code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

loud wharf
#

@lean sail It's normal to use interfaces and delegates to get around assembly definitions right? UnityChanThink

hollow pelican
#

Hey,
I have issue with 2D Colliders sometimes doesn't work when move fast. Video here: https://youtu.be/fO967SY2h8Q
Basically I want to rotate the Maze (green thing) and lead the ball to somewhere inside the maze.
this is the code I use to rotate the Maze:

        var rotationAngle = Time.deltaTime * rotateSpeed * playerInput;
        var rotationDelta = Quaternion.Euler(Vector3.forward * rotationAngle);

        rbList.ForEach(rb =>
        {
            var relativePosition = rb.position - (Vector2)transform.position;
            var rotatedRelativePosition = rotationDelta * relativePosition;
            var newPosition = transform.position + rotatedRelativePosition;

            rb.MovePosition(newPosition);
            rb.MoveRotation(rb.rotation + rotationAngle);
        });```
loud wharf
#

@hollow pelican Take a pic of the collider component to please. UnityChanThink

hollow pelican
loud wharf
#

I think I remember how to fix it, but go to look at collision detection, and set it to continuous.
Try doing it for the ball only.

#

If there's no such option or it doesn't work, idk.

hollow pelican
#

yes, the ball as "Continuous"

#

i have tried to tweak the Time also, but the issue still happen

loud wharf
#

Yeah idk. UnityChanPanicWork

lean sail
lean sail
loud wharf
#

Trying to separate the entities and weaponry to different assemblies. And weaponry kinda needs to gather a few things from entities. UnityChanPanicWork

fluid lily
#

Is there any reason PrefabUtility.InstantiatePrefab(edgePrefab, transform) would return null? Like not throwing an error, but returning a null object?

#

Ah figured it out. I had an object in scene of the prefab, so I saw the prefabs name and thought it was selecting a prefab.

obsidian trench
#

transform.position = Vector2.Lerp(transform.position, targetPosition, percentageComplete);
i want only the x component of transform.position to lerp how to do that?

mint vector
#

any way to run this in a seperate thread

#

it runs every frame and is pretty slow

thin aurora
#

Don't crosspost your question

mint vector
#

aight

hollow pelican
lean sail
#

Oh it's probably due to it being 2d

hollow pelican
#

yes, it's 2D

lean sail
#

Try setting interpolate then, maybe on both the ball and maze if they're both moving fast

lean sail
hollow pelican
#

it's on FIxedUpdate()

hollow pelican
lean sail
#

Typically it's just for the player character to smooth out jittery looking movement

hollow pelican
#

doesnt work :), i tried to set Interpolate on each one and then both, still have the issue

lean sail
#

If none of the settings work, then you are likely moving something based on frame rate

#

Continuous alone really shouldve solved it

river kelp
#

Is there a best practice setup for sending information between scenes? For example after a battle I want to output the result of the battle to the next scene, so it can be used to correctly alter the game state of the main game field.

#

I can think of a bunch of dirty methods using static variables etc but it seems a bit dirty.

hollow pelican
normal dust
#

if anyone here knows disco zoo, do u think the animals fitting in the grid is an algorithm? or based on predefined options and locations?

upbeat dust
#

Heyy, Eulers are pretty confusing.
I have object A, with a local rotation to a parent.
And object B which is a child of a scene

I want to set rotation of object B, same as object A

Should i use transform.Rotation, or Eulers?

lean sail
hollow pelican
normal stump
#

hey

hexed pecan
normal stump
#

how do I rotate a single bone in an animation from code?

#

I just want to orientate the moving animation towards the direction

hexed pecan
normal stump
normal stump
#

thanks

#

got another question

#

I'm using this method to get an angle of my character compared to movement direction

        var velocity = PlayerController.RB_Main.velocity.normalized;
        var charTransform = PlayerController.CharacterTransform;
        float angle = Vector3.Angle(velocity, charTransform.forward);
        return angle;

but my problem is that the angle is always positive

#

how can I get a negative and positive angle

#

like if I look towards left from direction it should be negative

cosmic rain
normal stump
#

no I didn't

cosmic rain
#

Checking the docs should be the first thing you do when having a question like that.

normal stump
#

sure

loud wharf
#

There's two ways I know of, one is transform.position which is literally displacing them and setting the velocity of the rigid body which lets Unity do some physics on it.

ruby fulcrum
#

how do i set chromatic aberration weight in volume component through script

turbid surge
#

It guides you through how to get to volume overrides and then how to access different parameters

#

You would need to TryGet the chromatic aberration override

turbid surge
#

👍

ruby fulcrum
#

when i use the default it gave me an error

crude mortar
#

show the whole line and the error

turbid surge
#

Use the one your pipeline uses

ruby fulcrum
#

im using the volume component

crude mortar
#

why do you have URP, HDRP, and PostProcessingStack installed?

#

which one are you actually using?

turbid surge
#

Also how are you getting the volume component

ruby fulcrum
#

im using urp

#

referencing it through serialization

crude mortar
#

then use the URP version of everything, make sure you aren't using the wrong namespaces. You are currently trying to use the PostProcessingStack ChromaticAberration but you need the URP one

turbid surge
ruby fulcrum
#

.profile

ruby fulcrum
crude mortar
#

no, I mean in code

ruby fulcrum
#

oh

crude mortar
#

the volume holds Rendering.Universal post processing effects if you are using URP, which is this one

turbid surge
#

^^

ruby fulcrum
#

alr

granite nimbus
#

can this ever return null? I'm pretty sure Application.dataPath always has parent. or this isn't what rider is pointing out?

crude mortar
#

I dont think rider would analyze that deep, it's just warning you that technically GetParent can return null, even though that might be impossible in this case

#

you could suppress the warning

ruby fulcrum
#

its giving me this error for the tryget line

crude mortar
#

are you sure you properly dragged the volume component into your serialized variable in the inspector?

#

and if so, are you sure you don't have multiple of these scripts in the scene where one of the scripts could have nothing dragged in?

granite nimbus
#

you could suppress the warning
TIL that instead of ? which is doing null check I can just write ! which suppresses the warningUnityChanCelebrate

upbeat dust
#

I have 2 objects.

Object A : is child of the scene
Object B : is child of many parents, each parent has its own local rotation to higher parents

I want to set rotation of object A = rotation of object B So in the scene they would be equally rotated

After several failed attempts i couldnt execute this in code, could someone help me

crude mortar
#

in newer versions of C# I mean. They really want the programmers to be aware of when things can or can't be null

granite nimbus
crude mortar
#

that's because I just made it up (I just mean they are forcing people to write ! and ? all over the place, i.e. be explicit)

crude mortar
#

and describe what goes wrong?

granite nimbus
#

is C# 9 considered newer version?

#

or modern*

normal stump
crude mortar
normal stump
#

C# 12 will come out end of year

granite nimbus
normal stump
granite nimbus
#

don't quite see relation between .net runtime, mono, il2cpp and language version 😄

normal stump
#

tldr; it takes a lot of effort to support the new IL standards

granite nimbus
#

mono and il2cpp are just harder to port to newer c#?

#

right?

normal stump
#

unity is still behind because it takes a ton of effort to rewrite IL2CPP I'm sure

granite nimbus
#

I see, thanks 🙂

crude mortar
upbeat dust
# crude mortar can you show your most recent attempt?

Sure, so the ultimate goal is to instantiate a bullet, which is a child of the scene
Then, there is a gun, which consists of several parts (parents) each with their own rotation relative to other parents

When firing (instantiating) the bullet, i want to instantiate it at the same rotation as the gun barrel.
(Note: after instantiating, i set rigid velocity to forward)

Problem: after trying to use Euler Angles, local rotation, and everything i could think of. The bullet kept coming out at a different angle than the gun barrel, and wasnt moving exacly forward (direcly towards blue Z arrow)

GameObject Bullet = Instantiate(BulletObj, GunBarrel.transform.position, GunBarrel.transform.rotation);

crude mortar
#

are you sure your bullet isnt just hitting your player collider?

#

or something along those lines?

#

because, right now, that code looks fine

upbeat dust
crude mortar
#

well, after instantiating, log the position of the gun barrel and the position of the bullet

#

you should see that they are identical

#

so yeah I would check through everything and make sure something else isnt moving it after, but I can assume that its something to do with the physics

cursive gorge
#

I need to negative array index for procedural map generation and i make this class, is that good?

class MArray<T>
{
    private T[,] _Array;

    Vector2Int zero;

    public MArray(int x,int y)
    {
        _Array = new T[x * 2 - 1,y * 2 -1];
        zero = zeroPoint();
    }

    public T this[int x,int y]
    {
        get
        {
            return _Array[zero.x + x,zero.y + y];
        }
        set
        {
            _Array[zero.x + x, zero.y + y] = value;
        }
    }

    Vector2Int zeroPoint()
    {
        int x = ((_Array.GetLength(0) - 2) / 2) + 1;
        int y = ((_Array.GetLength(1) - 2) / 2) + 1;
        return new Vector2Int();
    }
}```
crude mortar
#

your zeroPoint method will always return 0,0, and your array dimensions are a bit confusing (I dont think you should be subtracting 1)

cursive gorge
crude mortar
#

your zeroPoint method returns 0,0 because you aren't actually using the X and Y variables you created

fervent furnace
#

You can just set zero.x to x and zero.y to y (or there maybe a +1

cursive gorge
fervent furnace
#

No, there is no +1 term

cursive gorge
#

this thing has a problem (it's not really a big problem) because of its logic that it can't create an array of even number sizes

crude mortar
#

I just wouldn't offset the internal array

#

instead, I would do calculations when I am trying to index the array with a position or something

#

and the calculations would turn the position into an array index

fervent furnace
#

[0,x-1) x-1 [x,2x-1)
0 needed to be mapped to x-1 so zero.x=x-1

cursive gorge
#

there is a 5,5 MArray example (x and y swapped xd)

crude mortar
#

yeah I mean it works

#

if that's what you want to do then go for it

leaden ice
crude mortar
#

they double their size inputs for some reason so it would actually have -9 -9

#

its more like an extents parameter

leaden ice
#

I see

cursive gorge
#

zero point is also counting

fervent furnace
#

I have done some array similar to your case but i use a offset pointer

cursive gorge
crude mortar
#

what was the question again? this seems to work for what you want

cursive gorge
#

It seems to serve as an calculating layer in terms of converting world positions to grid array positions that I will be using for chuck and voxels loading system.

fervent furnace
#

If the T is struct then you cannot directly modify the members of struct
So i use unsafe list and pointer

cursive gorge
#

Will this cause a possible memory problem?

granite nimbus
cursive gorge
granite nimbus
granite nimbus
#

classes are reference types, which means all you store in your variable is just a pointer

#

which means almost free passing around

#

structs are value types, which means you actually store your value in your variable

#

I think this whole lightweight vs highweight comparison is pretty much irrelevant

#

they are just different

cursive gorge
cosmic rain
#

Lightweight vs heavyweight is not entirely irrelevant. If you make most of your class variables structs(where they could be a reference type), your classes would consume more memory. It depends on how heavy your structs too, but if, let's say, you need the same data to be accessed in 2 classes and you use structs for that data(sync it by copying it around or something), then you technically consume twice as much memory as you could if you were using a class.

#

It's not as simple of course, but the gist of it: use the appropriate data structure.

granite nimbus
cosmic rain
#

You could.🤷‍♂️

#

Or you could be obsessed with structs and only use them from the very start. That's the situation that I'm trying to warn against.

granite nimbus
#

well as you pointed out, struct can be higher weight depending on usage, that's why I advise against comparing them by this "weight", instead I think one should consider more exact and detailed differences, such as value vs reference, managed vs unmanaged, heap vs stack, pitfalls when passing them in and out of methods, etc
because applying paradigm "struct is lighter" we might (and will) end up just assuming struct is better when it's ever applicable, which is just wrong

quartz folio
#

You can certainly cause more performance problems by using structs without understanding how they're allocated and when, vs just using classes

loud radish
#

hey guys, i am working on a project where i have to load prefabs online into my app
and i am using asset bundle for that, its downloading alright but i need to know how can I keep the model downloaded and if i open it a second time it should load from cache or anywhere without internet, i believe it's simple question i am just not able to find any source which does it, can anyone help on this

#

please help stuck on for 2 days now 🥲

unique jolt
#

Hi guys, I don't know where to ask this issue...
My entire Unity project 2d start to go very slow, between 2-9 fps.
The project is really soft so I don't know why its so slow
Somebody could help me please?

heady iris
#

use the profiler

#

Window > Analysis > Profiler

#

run the game for a bit. you'll see a line graph up top. click anywhere in that to pause and examine that frame

potent sleet
#

haven't used asset bundle much though so take it with grain of salt

unique jolt
heady iris
#

one thing that comes to mind

#

i made this mistake several times

#

i would export a model from Blender and forget to exclude the camera that was in the scene

#

Unity would say "oh, you want a camera?" and create a camera for every single instance of that model

#

game grinds to a halt

unique jolt
heady iris
#

ah, hm

#

so the editor is doing something weird

#

have you restarted it

fervent furnace
#

do you open many editors?

unique jolt
#

like 2 fps

#

Ahhhm I have opened another unity project in this time

#

2 project open

#

I just closed it but nothing

#

The problem started after I have imported some audio

mild orbit
#

Quick question. Anyone know if it is possible to force raycast a disabled collider?

late lion
mild orbit
haughty bobcat
#

I use this assets to get folder path https://assetstore.unity.com/packages/tools/gui/runtime-file-browser-113006 and this code to load audios, some mp3 files give infinite error loop ```csharp
IEnumerator loadSong( GameObject obj )
{
FileSystemEntry song = getSong( obj.GetComponentInChildren<TextMeshProUGUI>().text );

    if ( song.Path != null )
    {
        AudioClip audioClip = getAudioClip( song.Name );
        if ( !audioClip )
        {
            loadingObj.SetActive( true );

            using ( UnityWebRequest request = UnityWebRequestMultimedia.GetAudioClip( song.Path, AudioType.UNKNOWN ) )
            {
                yield return request.SendWebRequest();

                if ( request.result == UnityWebRequest.Result.Success )
                {
                    AudioClip requestClip = DownloadHandlerAudioClip.GetContent( request );
                    requestClip.name = song.Name;

                    if ( requestClip.length > 0 ) songClips.Add( requestClip );
                }
                else
                {
                    Debug.Log( "Error loading audio: " + request.error );
                }
            }

            loadingObj.SetActive( false );

            yield return null;

            StartCoroutine( loadSong( obj ) );
        }
        else
        {
            ResetUI();

            Toggle songToggle = obj.transform.GetComponentInChildren<Toggle>();
            audioSource.clip = audioClip;

            songToggle.isOn = true;
            audioSource.Play();
        }
    }

    yield return null;
}```

Use the Runtime File Browser from yasirkula on your next project. Find this GUI tool & more on the Unity Asset Store.

#

This line >>> AudioClip requestClip = DownloadHandlerAudioClip.GetContent( request ); gives infinite error loop

#

Im not sure how to avoid that I've tried try{}catch but nothing

leaden ice
#

share actual errors etc.

haughty bobcat
#

gimme a sec to recover the error

#

this infinite error loop Error: Cannot create FMOD::Sound instance for clip "" (FMOD error: Unsupported file or audio format. ) UnityEngine.Networking.DownloadHandlerAudioClip:GetContent (UnityEngine.Networking.UnityWebRequest) MusicFolderScanner/<loadSong>d__17:MoveNext () (at Assets/_Assets/_Scripts/_Menu/MusicFolderScanner.cs:155) UnityEngine.SetupCoroutine:InvokeMoveNext (System.Collections.IEnumerator,intptr)

#

The audio format is mp3

#

This happens with some audios and the other load fine

leaden ice
#

what do you mean by "infinite" error. I'd say the reason you're getting the rror overr and over again is because you are calling the coroutine recursively:
StartCoroutine( loadSong( obj ) );

haughty bobcat
leaden ice
#

I'd guess the audio file for that particular clip is corrupted or otherwise unsupported by Unity

late lion
haughty bobcat
late lion
#

Then there's probably some feature of the MP3 file format being used in those files that Unity doesn't support.

haughty bobcat
late lion
#

You can look into using NLayer to convert the MP3s to PCM/float[] samples, which you can then feed into AudioClip.SetData.

haughty bobcat
naive swallow
#

A file in MP3 format could be encoded many different ways. The encoding could be different on this one

haughty bobcat
naive swallow
#

Try re-encoding it in Audacity

haughty bobcat
#

I changed this line and now the error only shows once csharp if ( requestClip.length > 0 ) { songClips.Add( requestClip ); StartCoroutine( loadSong( obj ) ); }

leaden ice
#

your clip/file is not supported by unity for some reason

haughty bobcat
#

and how I can let a user know that their audio doesnt work if it gives that error?

leaden ice
#

show a UI element with an error message?

#

Have a little creature jump up and say something to them?

#

whatever you want.

#

Try/catch is a good way to detect the error

#

assuming it actually throws an exception

#

it's unclear if it does

haughty bobcat
#

if I put an else statement in that last line it should work I guess

leaden ice
#

If that works then it's not actually throwing an exception

#

in which case yeah, that's fine

haughty bobcat
#

Bruh even audacity doesn't recognize the audio

leaden ice
#

well there you go

#

it's a corrupt file

lean sail
#

Cant imagine many things would work with a corrupt file

haughty bobcat
#

doing what it says there is just static

#

The thing is in a windows audio player it works fine

lean sail
haughty bobcat
#

Let me use a page converter to see if it works

lean sail
#

it might just be some format used that audacity/unity doesnt accept

#

theres probably a site u can see what it really is, idk much about audio but it should have information in some header

wide terrace
#

It appears to be a mpeg-4 aac codec... I can only find mentions in the Unity docs of supporting mpeg 1-3. From a Unity rep on the forums in 2021:

the last time I checked, mp4a was not supported. So even if it happens to work on some platforms, we don't support it across all of them.

haughty bobcat
#

with .wav it works

#

Is there a way to check if the audio is mpeg-4codec?

#

That way I dont get that error

lean sail
#

probably a site online

haughty bobcat
#

it says 2 / 40 / mp4a-40-2

lean sail
#

mp4a is the part u care about there then

haughty bobcat
#

Is there an extension or plugin I can use in unity to auto convert this to mp3 or wav so I dont get that error?

wide terrace
#

You could probably package up ffmpeg/ffprobe with your game and use it to determine codecs, or even convert the file on the fly... I have no idea how large of a headache that might be though 😁

#

There's probably something on the asset store which does so - I'd search "ffmpeg"

haughty bobcat
#

mmm let me see

#

sadly that asset is paid 😔

neon plank
#

How can I clone a NavMeshData? I want to have two copies which are different objects.
Basically, I want to be able to do:

NavMesh.AddNavMeshData(data, positionA, rotationA);
NavMesh.AddNavMeshData(data, positionB, rotationB);

However, I noticed that if both datas are the same object, only the last data is added.
So I need a way to clone it.

haughty bobcat
lean sail
haughty bobcat
#

still how I can check if it is mp4

#

Seems this gets skipped private string[] validExtensions = { ".wav", ".mp3", ".ogg", ".aif", ".aiff", ".flac" };

lean sail
#

well idk where u use that in your code

late lion
haughty bobcat
#

chatgpt sayd to convert it use ```csharp
using NAudio.Wave;
using System.IO;

public class AudioConverter : MonoBehaviour
{
public string inputFile;
public string outputFile;

void Start()
{
    ConvertToMp3(inputFile, outputFile);
}

void ConvertToMp3(string inputFilePath, string outputFilePath)
{
    using (var reader = new MediaFoundationReader(inputFilePath))
    {
        WaveFileWriter.CreateWaveFile(outputFilePath, reader);
    }
}

}

lean sail
#

awkwardsweat chatgpt

neon plank
#

When I use instantiate, only the last NavMesh.AddNavMeshData is shown in the scene view. So I think they are still sharing some internal state

haughty bobcat
lean sail
#

ive only done it in other languages so i cant really suggest a c# method for it

haughty bobcat
lean sail
#

system io will help u get the path extension if that was an issue

haughty bobcat
#

nah the path is fine I use a file browser to get the folder then add the filename after

lean sail
#

i mean file extension*

haughty bobcat
#

it was just the audio format that it gave error

wide terrace
lean sail
#

the data should just be at the start, and you'll be able to find how many bytes it is online

haughty bobcat
#

with NAudio it gives this error I used audio importer asset csharp Got a frame at sample rate 44100, in an MP3 with sample rate 11025. Mp3FileReader does not support sample rate changes. UnityEngine.Debug:LogError (object) ImporterExample/<Import>d__5:MoveNext () (at Assets/AudioImporter/Examples/ImporterExample.cs:30) UnityEngine.SetupCoroutine:InvokeMoveNext (System.Collections.IEnumerator,intptr)