#archived-code-general

1 messages ยท Page 49 of 1

wispy wolf
#

I want to know if my player has a positive velocity along a given axis. I have the velocity as a vec3 and the axis as a normalized vec3. I can use Vector3.Project(vel, norm).sqrMagnitude to know if there is any velocity along the normal, but how would I know if this is along the normal or opposite the normal?

wispy wolf
#

Dot products always confuse me

#

I should probably find a good explanation

somber nacelle
#

returns 1 if they point in exactly the same direction, -1 if they point in completely opposite directions

wispy wolf
#

So basically how similar they are on a scale of -1..1?

rustic rain
#

how can i reset material values when theyve been altered in code?

latent latch
#

Materials are usually persistent data. If you're altering them at runtime you're probably making a new instance of them, so what you will probably want to do is either cache the original values or find a way to create another instance.

wispy wolf
#

If I have a velocity of Vector3(1,1,1) and I want to change the velocity on the Z to 0.3 I can just set vel.z = 0.3. But what if I want it to be 0.3 on an arbitrary axis normal like (0.5, 0.5, 0)?

leaden ice
thin frigate
#

Alright does anybody have any idea why my instanced GameObjects are destroying themselves after exactly 1.6 seconds

maiden breach
#

Ctrl-F "destroy" in your project in VS

thin frigate
wispy wolf
rustic rain
#

i seem to have screwed up my damn ui materials

#

its because i was changing offset of stuff, how can i fix this

maiden breach
#

git revert

cosmic rain
rustic rain
maiden breach
rustic rain
wispy wolf
maiden breach
cosmic rain
leaden ice
rustic rain
#

how do i disable visual scripting?

leaden ice
#

Uninstall the package

wispy wolf
neon plank
#

Did someone had problems updating Burst compiler from 1.8.2 to 1.8.3?
I updated correctly, but a workmate pulled the commit and he got an error when importing the package. He tried uninstalling the package, reboot Unity (which automatically installed 1.8.2) and then updated to 1.8.3 but got an updating error...
We are using 2022.2.5f1.

winter flower
#

So I'm using blender, and I got this error using a qc file

potent sleet
#

this is Unity dc, and coding channel

outer apex
#

I have a script with a public list attached to a game object but the public list isn't showing up in the inspector. am I missing something?

potent sleet
#

if it's custom class or struct you need the System.Serializable for it

outer apex
#

ohoho you're a genius

#

I bet that's it

#

absolutely was, thank you!

#

ack what a dummy. I did this to debug my inventory system. I wrote the complex part where if you get something it tries to merge stacks with what's there. forgot to do the other part where if there's no stacks, it just makes a new stack 9_9

#

in Unity is there such a thing as a "frill blocker" - aka some way to suppress a terrain's detail layers in a space on a temporary basis? or do I really have to edit the detail map each time?

fresh hull
#

So my player has many scripts attached to it, many of these Scripts reference each other, but because Networking is hard and it messed up my head, I ended up using 2 types of referencing throughout my project.

The first way is the common one which is to just [SerializeField] the class that i need, Like "" Oh i need to verify if the player is grounded here on the gun script"", So i just serialize and set it in the inspector

The other way is to have a Player class that holds all the scripts in the player and if i need something i just do ""Player.Movement.."" etc

Does using the second way for all my references affect performance?
do i need to cache it on start or is just asking the Player for the script fine every frame?

Uhh that was long, if anyone can answer i'd be thankful

leaden ice
#

the bigger question is do you really want to tie all the references to your Player object

#

that kind of hard couples everything to this Player script

fresh hull
#

hmm, you have a point

#

imma try and clean things up and leave the player class just for spawning and saving the current server players

pale owl
#

If I made a Serialized Field called Sounds. Its a list of sounds in my Audio Manager's inspector. How do I get the first int in the list to change its Audio Clip.

Just the first bit of the code. I'm basically trying to do this.

the first sound in the list = this.musicObject.GetComponent<AudioSource>();

#

Theres a GameObject I have attached to the Audio Manager that I want the first in the list to be equal to

#

Looks like this

#

would it be like... sounds[0] =

#

or something

leaden ice
#

but likely... sounds[0].clip = something;

pale owl
#

kk

#

OwO

#

Lemme try that and then send my code if it doesnt work. (Also thank you)

#

[System.Serializable]
public class Sound
{
    
    public string name;
    public AudioClip clip;

    [Range(0f,1f)]
    public float volume = 0.7f;
    [Range(0.5f,1.5f)]
    public float pitch = 1f;

    [Range(0f,0.5f)]
    public float randomVolume = 0.1f;
    [Range(0f,0.5f)]
    public float randomPitch = 0.1f;

    public bool loop = false;

    private AudioSource source;

   

    public void SetSource (AudioSource _source)
    {
        source = _source;
        source.clip = clip;
        source.loop = loop;
    }

    public void Play ()
    {
        
        source.volume = volume * (1 + Random.Range(-randomVolume / 2f, randomVolume / 2f)); ;
        source.pitch = pitch * (1 + Random.Range(-randomPitch / 2f, randomPitch / 2f)); ;
        source.Play();
    }
    public void PlayWalk()
    {
        source.volume = volume * (1 + Random.Range(-randomVolume / 2f, randomVolume / 2f)); ;
        source.pitch = pitch * (1 + Random.Range(-randomPitch / 2f, randomPitch / 2f)); ;
   
            if (!source.isPlaying)
            {

                if (source.isPlaying == false)
                {
                        source.Play();
                }
            }
    }

    public void Stop()
    {
        source.Stop();
    }

}
#
{
    public GameObject musicObject;
    public static AudioManager instance;

    [SerializeField]
    Sound[] sounds;
    

    private void Awake()
    {
        if(instance != null)
        {
            if(instance != this)
            {
                Destroy(this.gameObject);
            }
        }
        else
        {
            instance = this;
            DontDestroyOnLoad(this);
        }
    }

    private void Start()
    {
        for( int i = 0; i < sounds.Length; i++)
        {
            GameObject _go = new GameObject("Sound_" + i + "_" + sounds[i].name);
            _go.transform.SetParent(this.transform);
            sounds[i].SetSource (_go.AddComponent<AudioSource>());
        } 
        PlaySound("Music");
    }
    public void PlaySound(string _name)
    {
        for (int i = 0; i < sounds.Length; i++)
        {
            if(sounds[i].name == _name)
            {
                sounds[i].Play();
                return;
            }
        }
        //no sound with _name
        Debug.LogWarning("AudioManager: Sounds not found in list, " + _name);
    }
    public void PlayWalkSound(string _name)
    {
        for (int i = 0; i < sounds.Length; i++)
        {
            if (sounds[i].name == _name)
            {
                sounds[i].PlayWalk();
                return;
            }
        }
        //no sound with _name
        Debug.LogWarning("AudioManager: Sounds not found in list, " + _name);
    }
    public void StopSound(string _name)
    {
        for (int i = 0; i < sounds.Length; i++)
        {
            if (sounds[i].name == _name)
            {
                sounds[i].Stop();
                return;
            }
        }
        //no sound with _name
        Debug.LogWarning("AudioManager: Sounds not found in list, " + _name);
    }

    public void SwitchMusic(int sounds)
    {
         sounds[0].clip = this.musicObject.GetComponent<AudioSource>();
    }
}
#

Sorry its a big code

#

Idk if theres a way to shrink it in discord or not ๐Ÿ˜…

leaden ice
#

yep - sounds[0].clip = whatever;

leaden ice
#

!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.

pale owl
#

Ok thank you

#

sounds[0].clip = this.musicObject.GetComponent<AudioSource>();

#

I tried that

#

It comes up with an error under the sounds part of the code

leaden ice
#

not an AudioSource

#

you can't put an AudioSource in an AudioClip variable

#

what are you actually trying to do

#

I think you have this backwards

#

I think you want to set the clip of the audio source to the clip from your sounds array

pale owl
#

I'm trying to make it so that when I switch scenes, the music in the AudioSource will change to be the music indicated in the object "Music" in the scene

leaden ice
#

I'm 90% sure you actually want something like this:

public void SwitchMusic(int index)
{
    AudioSource source = musicObject.GetComponent<AudioSource>(); // why isn't this just a direct AudioSource reference????
    source.clip = sounds[index].clip;
}```
pale owl
#

My Audio Source holds and controls all audio in my game. Jumping Landing attacking etc...

So I want my music audio to change when I switch only to a specific scene.

#

Idk maybe that'll work ๐Ÿ˜…

leaden ice
#

Also your code is kinda insane

#

seems like you have 2-3 duplicate methods that do the same thing

ocean oasis
#

Hi! Long story short, I want to have a list of terrain objects that spawn their own named empty object to be used as a parent. The tool updates automatically whenever a new element is added or taken away, but the implementation is quite messy.

My question is: If I were to remove an element of the list within the Inspector, is there any way to, through code, find out exactly what object was removed without the manual, keeping copies of the list and checking for differences?

pale owl
#

I'll try it.

#

Thanks ๐Ÿ™‚

hoary ginkgo
#

ChatGPT just generated a solution to a problem I was stuck on for hours lol

#

And the code was simpler and cleaner than anything I could find online

ocean oasis
pale owl
# leaden ice Yep seems like this is what you want

Ok so I did the thing. It definitely is doing something and plays the music, but now it doesnt play the music continually when I switch scenes which was the purpose of making the Music section of the audio manager.

I think maybe if I call upon a script in the musicObject it might work, but I'm not sure.

#

BUT You definitely fixed my problem with finding out how to get that code to run.

#

So thank you. It helped me.

hoary ginkgo
leaden ice
hoary ginkgo
#

Yeah well your mom.

leaden ice
#

The question is - did you actually learn anything?

hoary ginkgo
#

Yes I did lol

leaden ice
#

If you did then good

ocean oasis
hoary ginkgo
#

I was using A* Pathfinding but I'm not sure if I'm going to keep using it. There are simpler solutions

pale owl
#

Sorry for @ing you again ๐Ÿ˜ฎ

Lemme know if I shouldnt do that.

#

I also tried changing index to 0

deep willow
#

how do i change a variable's name ? Also, if i change the name of a variable, does it affect the value of that variable in the inspector?

#

i want to change the name of a variable everywhere in code

pearl otter
#

How do I set the speed of AddForce()?

cosmic rain
pearl otter
#

Yes ๐Ÿ™‚

cosmic rain
#

That question doesn't make any sense.

pearl otter
#

It makes perfect sense

#

Right now when the player jumps, they jump way to fast, I want to slow it down

cosmic rain
#

It doesn't.
AddForce() is a method. It doesn't have a speed property that you can set.

pearl otter
#

What should I use then?

cosmic rain
#

You misunderstood my reply. I was talking about how your question does t make sense.

#

You can still use AddForce for jumping.

pearl otter
#

How can I slow it down?

cosmic rain
#

Just reduce the force that you pass into it.

pearl otter
#

Wouldn't that make the player not jump so high then?

cosmic rain
#

It depends on how you apply the force. If you apply it regular force over time, as long as it's higher than gravity, it will move the object up.

#

Basically each frame you'd be applying an acceleration equal to jump force - gravity force.

#

If you're using an impulse mod, that's a different story though

pearl otter
#

So I should use the Force Mode?

cosmic rain
#

Again, depends on what kind of implementation you want.๐Ÿคทโ€โ™‚๏ธ

pearl otter
#

I just want the player to jump lol

cosmic rain
#

If you want more control over it you could even set the velocity manually

pearl otter
#

How might that be done?

cosmic rain
pearl otter
#

Setting the velocity gives the same result as AddForce unless I am doing something wrong

stray stratus
#

how would I change the fog settings from code? I want to use the default built-in fog I think in the lighting menu. I want to change the color and thickness, but I haven't found any way to do that. Anyone know how?

cosmic rain
pearl otter
cosmic rain
#

On that line nothing.

pearl otter
#

Well what other line would there be?

cosmic rain
#

I don't know. I don't have your script...๐Ÿ˜…

#

Reducing jumForce should reduce the velocity.

pearl otter
#

That would just make the player not jump so high then though

cosmic rain
cosmic rain
pearl otter
#

You told me to do this facepalm

cosmic rain
#

I only told you that you can have more control over it if you set velocity.

pearl otter
#

But I need control on the speed lol

cosmic rain
#

There are a lot of other factors that could affect the whole jumping mechanic.

cosmic rain
#

It sets the "speed" directly

pearl otter
#

Huh..

cosmic rain
pearl otter
#

rb.velocity = new Vector2(rb.position.x, jumpForce);

cosmic rain
#

250 speed is a lot btw. That's why it looks like they're teleporting

#

75

pearl otter
cosmic rain
#

75 is still a lot

pearl otter
#

I need it to jump that high

cosmic rain
#

It means 75 units/s. Which is more than 1 unit per frame.

pearl otter
#

It needs to be able to jump over the blocks

pearl otter
cosmic rain
#

I see that it's really weird, but not much I can do without seeing your code.

pearl otter
cosmic rain
#

There's clearly something resetting the velocity of the character.

pearl otter
#

Because it doesn't

cosmic rain
#

Well, that's just how it looks like on the video. I can't say for sure because I don't see your code.

#

Anyways, if you know better, then why even ask here?

pearl otter
#
        isGrounded = Physics2D.OverlapCircle(groundCheck.transform.position, 0.2f, collidableLayer);

        if (Keyboard.current.wKey.wasPressedThisFrame || Keyboard.current.spaceKey.wasPressedThisFrame) shouldJump = true;

        if (shouldJump)
        {
            shouldJump = false;
            if (isGrounded) rb.velocity = new Vector2(rb.position.x, jumpForce);
        }```
cosmic rain
#

That part is fine.

pearl otter
#

That is my code

cosmic rain
#

I bet there's more code than that.

pearl otter
#

Not trying to be rude, but you shouldn't be trying to help people here if you don't know much about coding.

cosmic rain
#

That's funny, but ok.
If you don't want to cooperate, then good luck solving the issue on your own.

pearl otter
pearl otter
pearl otter
#

What other script?

cosmic rain
pearl otter
#

I gave you my code from the beginning

cosmic rain
#

Or where do you have your movement code?

pearl otter
#

You don't need my entire class, you just need my jump code

pearl otter
cosmic rain
#

Then share it...

pearl otter
cosmic rain
#

Ok, good luck then...

pearl otter
#

Thank you.

cosmic rain
#

If you change your mind and decide you need help after all, feel free to share the whole script.

pearl otter
#

You're funny ๐Ÿ™‚

vagrant blade
#

@pearl otter If you're not going to share your code in entirety for review, then please refrain from posting questions.

#

Also as mentioned above, you'll need to modify velocity each frame, and manually reduce it by some deceleration factor until it reaches 0, if you want to fine tune how much and fast you jump.

pearl otter
vagrant blade
vagrant blade
pearl otter
vagrant blade
#

I did go through it. ๐Ÿ‘

pearl otter
#

Great

#

None of my other code related to the jump, so there is no reason to send it.

hexed pecan
#

Its just absoultely wrong and doesnt make sense. I didnt even notice it at first

cosmic rain
#

They seem to know better than us Osmal. It's useless to argue with them.๐Ÿ˜ฌ

pearl otter
#

I just grabbed some movement code from online but I got it working now

swift falcon
#

Hi, I have a UI button that increases the number on a UI Text every time it is pressed, however I would like to carry out this increase whilst the button is held down rather than pressed once. Any help would be appreciated

pearl otter
#

I'm not entirely sure how you check if the button is held down though

cosmic rain
#

With a custom button you can implement the IPointerDown/UpHandler interfaces.

hollow karma
#

So I'm using a coroutine to make my character jump

#

the coroutine checks if the player can jump for a few frames after they press the input

#

that way it feels more responsive

#

but

#

if the player spams the jump button

#

the player jumps super high

#

im assuming its because there are multiple coroutines running at once

pearl otter
#

Just to confirm, you are checking if the player is on the ground right?

hollow karma
#

yes

#

sorry should have clarified

pearl otter
#

Try moving that code to the end of the coroutine when the jump code runs

cosmic rain
#

Cache the new coroutine and check if it exists before starting a new one. Reset the reference when done jumping.

pearl otter
#

Or you could actually use a variable

hollow karma
#

i figured that would do the same thing

#

but the problem persists

hollow karma
cosmic rain
hollow karma
#

i am doing the groundcheck in the coroutine

cosmic rain
#

!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.

hollow karma
#

sorry the code is too long to zsned in discord

#

let me try one to the websites

hollow karma
#

here that should be my code

cosmic rain
hollow karma
#

i tried multiple ways

pearl otter
#

No it won't but if I am reading your code correctly, the player shouldn't be jumping in mid air

cosmic rain
hollow karma
#

sorry if that is a bit vague

#

i don't think i really understand how caching works

cosmic rain
#

Check the stop coroutine docs page. They have an example

hollow karma
#

not that the player jumps in midair

hollow karma
hollow karma
pearl otter
#

I would just create a variable "isJumping" or something, then when the player clicks the jump button, it sets the variable to true, then after the coroutine ends, set it to false. Then when the jump button is clicked, only start the coroutine if isJumping is false

hollow karma
pearl otter
#

I don't think so

#

Oh I see what he is saying

cosmic rain
#

You want to cache the Coroutine instance that you start.

hollow karma
#

ok

pearl otter
#

Awesome

#

No need to over complicate things. I often do that too lmao

hollow karma
#

nevermind :(

#

it seems to reduce the frequency of it happening

#

but it still happens

pearl otter
#

Hmm

hollow karma
#

i will resned my code

pearl otter
#

In StartJumpSequence(), can you use a Debug, we will be able to see if the function is being called multiple times

hollow karma
#

ok

hollow karma
#

and checkingJump seems to be true

#

when the glitch bounce happens

#

which is also wierd

#

but

#

the jump method is getting called 2 or 3 times when the glitch bounce happens

pearl otter
#

Ah

#

I'm not sure what your for loop is doing, but it looks like its running multiple times before the player jumps and/or the ground check is above the radius to the ground when loop repeats

hollow karma
#

what i was trying to do was

#

when the player pressed jump

#

the coroutine starts

#

it checks if the player can jump once every frame for a few frames

#

if at any time the player can jump the coroutine stops

#

and the player jumps

hexed pecan
#

Oh like inverse coyote time

hollow karma
#

the for loop just lets me control how many frames i can check for

hexed pecan
#

You press a bit early, and you want it to wait for landing and exectuing the jump then?

hollow karma
#

is that not what the for loop is doing?

pearl otter
hollow karma
#

alr

pearl otter
#

Also just a tip, if you are planning on making your variables changeable in the Inspector, you should make the variables private and use [SerializeField] unless you need to set the variable from another class

hexed pecan
#

I would start a coroutine when I jump but I'm not grounded/allowed to jump. I would also stop all existing coroutines when doing this.
You should use myCoroutine = StartCoroutine(...) to cache/store the current coroutine when starting, andStopCoroutine(myCoroutine) to stop any ongoing coroutines when it starts, like dlich was hinting

hollow karma
lyric wadi
#

can't you use checkingJump as a condition when starting the coroutine, not start another if that is true

hollow karma
lyric wadi
#

k

hollow karma
#

because checking jump shows if there is already another coroutine

#

i think

#

but im gonna try cahcing the coroutine instead

hollow karma
cosmic rain
hollow karma
#

like thers float and an int

#

is there a "coroutine"

pearl otter
hollow karma
#

right ok

pearl otter
#

You are storing the function, not coroutine

cosmic rain
cosmic rain
cosmic rain
hollow karma
hexed pecan
#

Umm yes

hollow karma
#

but don't we want to stop all the other coroutines?

hexed pecan
#

I also didn't read your code or the discussion in great detail, just saying how it can be done

hollow karma
pearl otter
#

You would need a list then but from your debug test, only one coroutine is being started

hexed pecan
#

Stop that, then start another one and cache it in

#

But if this isn't what the others are telling you, ignore me

hollow karma
#

ok

cosmic rain
#

It would be best to just set some flag when you actually started jumping and reset it when you're grounded.

hollow karma
#

ok

deep willow
#

how do i get the width and height of text?

#

im working on a tooltip that needs its background to fit the text within it

#

background is an image

hollow karma
#

but i think the way im checking if the player is finished jumping is a little clunky and/or not performant

#

right now, im checking if isJumping is true and the y velocity is less than 0 and the player is grounded

#

is there a simpler way?

cosmic rain
#

You just need to set isJumping to false at the start of the frame if you're grounded.

hollow karma
#

the problem is the player is grounded for a split second after isjumping is set to true (and the player jumps)

#

becuase my overlapspehere that checks for if its grounded is a little big

cosmic rain
#

So what? Your coroutine should be running by then.

#

You just need to avoid starting the coroutine if you're already jumping.

#

Aah.

hollow karma
#

im gonna try putting the jumping end check at the last line of fixed update

#

or maybe even lateupdate

#

so it happnes after the player is no longer "grounded"

#

maybe

#

nevermind

cosmic rain
#

I think you should just rework your ground check.

#

It's not ideal when it reports wrong results.

hollow karma
#

alright

deep willow
#

im trying to make a ui text object folllow the mouse using:

#

transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition);

#

but its in the bottom left corner all the time

#

it moves slightly when i move the mouse but why is it not moving right at the mouse position?

hexed pecan
#

Could try to modify the recttransform's anchoredPosition instead

deep willow
#

ah okay

nova narwhal
#

anyone got workin with epic sdk? platformInterface.Initialize doesnt work, throws null exception?

#
        {
            ProductName = m_ProductName,
            ProductVersion = m_ProductVersion
        };
 
        var initializeResult = PlatformInterface.Initialize(initializeOptions);         <------------
        if (initializeResult != Result.Success)``` crashes at initialize
swift falcon
#

y cant i drag "Text" into the "Result" field in the player script?

quartz folio
swift falcon
#

oh, did not know that

tidal shadow
#

@frosty scroll

isSameInteracted = (interactibleInstanceId != interactible.GetInstanceId();
CheckInteraction```
Instead of switch
#

Never used it myself

craggy veldt
#

not quite sure what you mean by stable... they're not persistent id so it would be changed on restart etc...
Regarding your question the answer is, it doesn't matter, you're good!๐Ÿ‘

mellow sigil
#

Just store the object references?

brittle sparrow
#

Whenever I uncomment this function, it gives 24 errors, all relating to not closing off a parenthesis or something and end-of-file stuff, but I checked it and it doesn't seem to have that sort of problem. Maybe there's a problem with using tuple arrays or params with tuples?

mellow sigil
#

I mean a better solution would be to not compare instance ids but compare instances instead

#

no

#

If there's any difference, it's so small that you can't even measure it. But comparing references is really fast, the reference is just an integer internally

#

on the other hand comparing strings isn't (relatively) fast at all

swift falcon
#

how to place some objects (meshes) in front of UI, and some behind UI ?

#

i can either get them all in front or all behind

#

not both in same time

mellow sigil
#

(don't remember if ids are strings or ints)

#

and you're doing extra method calls to retrieve the id in the first place

brittle sparrow
#
void somefunc<T>(params (bool b, T gen) paramfoo){}

for some reason this isn't possible, isn't there any workaround for this?

#

I could just use a struct perhaps, but any other ideas?

craggy veldt
brittle sparrow
#

wait but doesn't that only allow one argument?

#

yeah, it doesn't let me do this:

#

I was thinking of using structs, but I also wanted to have the cleanliness of tuple params as shown in somefoo()

craggy veldt
#

you mean like this? void Test<T>(params (bool b, T t)[] ppr){}

brittle sparrow
#

yeah, but it calls an error unfortunately

craggy veldt
#

wdym?

brittle sparrow
#

sorry i'm a genius

#

i forgot to put in []

#

i was sure i did why

craggy veldt
#

aight goodluck

brittle sparrow
#

I used return as a variable name

daring cove
#

Why does adding colliders inside colliders cause Physics.SyncColliderTransform take far longer?

I have made the colliders have different layers and in the Layer Collision Matrix the layers are set so that they don't collide with each other.

#

Active Constraints jumps from 382 to 147.97k with no reason

spring basin
#

hello, where do i post ad related queries?

elder flax
#

whats the best way to do a grid?

#

like some objects take up multiple tiles and I dont want other objects to intersect them

restive ice
#

Anyone have a better name for this test?

restive ice
# elder flax whats the best way to do a grid?

well you can utitilize tilemaps if it's a 2d game (they do work in 3d too), there's a Unity Grid component, but im currently writing my own Grid system that utitilizes that component to give me more robust controls

elder flax
restive ice
#

the 2nd way you can just draw on your tilemap to store things like 'cant place stuff here'

elder flax
#

how would checking if a certain shape can fit work on a custom grid system

#

im assuming it would use a 2d array

restive ice
#

then for each object I would store the offsets for each tile it occupies

#

those offsets would obviously change for each possible rotation of your object

#

then you check for the center, and for all of the offsets, if a tile is already occupied

#

you could also just set transforms and raycast to the floor and then turn that worldpoint into a grid coordinate I guess?

neon plank
#

Question: When using the Profiler TimeLine... is possible to highlight (or somehow make easier to find) method made by me? I mean, methods in my namespaces or maybe methods in the Assembly-CSharp assembly, or methods in an specific type?

#

Because there are so many stuff there that makes difficult to find my code

river wigeon
#

Hey guys, I was wondering if anyone could help with the structuring of game logic?

#

Currently I have something like this, which uses a lot of callbacks but it feels messy

#

and it's going to get longer with more and more nested timers

#

I'm thinking of trying to make states but I'm finding it a little confusing

#

Do I make states as a class for which I then pass in lambdas in the constructor for what the switching conditions are, or do I make it an abstract class or an interface and make a new class every time I want to define a new state?

#

Do I have to check the conditions every tick, or can I run states on a more event based system?

#

If I do make it an interface, how would I then define a bunch of states and chain them together, as lots of information needs to be shared between them

restive ice
river wigeon
#

I'm unsure of how to structure it however

#

I think I'm entering what is called 'callback hell'

#

in the game there's a president and a chancellor, and different states. President picks a chancellor, people then vote on the decision, then different things happen depending on what the result of the vote is etc

#

currently I have these nested timers

#

so in that screenshot I sent, I create a timer which lasts 30s and the president is asked to select a chancellor. If the timer runs out before the president selects a chancellor, a random president is picked. If the president does make a choice, the timer is stopped early. The next state of the game is nested inside that timer, where a new timer is then created and the process basically repeats

#

It feels like I'm doing things wrong

#

But I'm struggling to think of how to do it with more well defined states

restive ice
#

hmm

#

maybe look into interfaces and then use the observer pattern?

river wigeon
#

right

#

if I had an interface where would I actually define the classes

#

so would I make a new script for each state?

snow moat
#

hello,
Just a simple question : I try to switch to the Unity Localization package
BUT, I already have and interface that used in all my app
string Localize(string key)
As GetLocalizedString in the package seems to works only on Async way, I have a problem

Is there any equivalent function without async mode ?
Do you think of some workaround that prevents me to rewrite all my scripts that need localization ?

somber nacelle
#

you can call an async method from a non-async context, it will just run synchronously if you do

snow moat
#

but I will block the app some frame no ?

somber nacelle
#

yes, but so will any non-async options

snow moat
#

something as GetLocalizedString(x,y).Result ?

#

or maybe more GetLocalizedString(x,y).GetAwaiter().GetResult() ?

#

idk the equivalent for AsyncOperationHandle ๐Ÿ™‚

somber nacelle
#

whoops, wrong link. there's the correct one

snow moat
#

ok thanks !!

#

it works !! Thx for your help @somber nacelle

thin kernel
#

How to init BoxCollider with Bounds? You can't set it directly, and basic "center" and "size" is not enough when object is scaled or rotated.

Screen 1: White - bounds, green - box collider.
Screen 2 and 3: Object "bounds" is the same in both cases.

small trench
#

So u can do
Gizmos.matrix = transform.localToWorldMatrix;

#

U should call change the values of the Matrix before u draw with gizmos
And make sure this is also within OnDrawGizmos() or OnDrawGizmosSelected()

thin kernel
#

Gizmos is the correct one here, they are drawing my bounds as the should. I want my collider to be the same as the bounds.

small trench
small trench
thin kernel
#

@small trench Damn, you was right. But I still want the effect that I have with first gizmos on my screenshot. No easy way to rurn of matrix on the collider? XD

jagged laurel
#

script MouseLook

#

throw off

jagged laurel
#

everything is gone

hasty haven
#

Hey, i'm wanting to make currency in my game slightly less susceptible to simple cheat engine edits, curious how people might handle this?
This data is stored in a save file thats obfuscated a bit, relatively small, i don't care about perfect security just want to deter simple edits.
The only time I am currently reading from the file is when you load into a game from the menu and it stores that data in a temp PlayerData class.
Right now when you try to buy from a merchant it uses the value from that PlayerData class, so technically you could modify that at runtime.
Would it be more ideal if I get the true value from the save file each time you purchase something?

#

I'm mostly concerned about accidental read/write issues

copper torrent
#

Alright, so I'm using UI Builder with a ListView and this is my code:

        Debug.Log("First SOURCECOUNT:  " + keyListSearchParameter.Count);
        if (CompareList(keyListSearchParameter, (List<String>)keyList.itemsSource))
            return;
        keyList.itemsSource = keyListSearchParameter;
        baseBindItem = (e, i) =>
        {
            Debug.Log("SECOND SOURCECOUNT:  " + keyListSearchParameter.Count);
            (e as Label).text = keyListSearchParameter[i];
        };

        keyList.bindItem = baseBindItem;
        keyList.itemsSource = keyListSearchParameter;
        keyList.Rebuild();
        keyList.RefreshItems();
        UpdateTranslationCounter();

Can someone explain to my WHY the Debug.Log() lines create DIFFERENT output?!??!?!

thick socket
#

Coroutine...how do I wait for 1 frame?

#
yield return Wait(1);

would this do it?

#

(solutions I found online are outdated as I can't do this anymore

    yield return WaitFor.Frames(5); // wait for 5 frames
pearl radish
#

yield return null

thick socket
#
BackgroundButton.clicked += () => buttonClicked();

buttonClicked is a Coroutine...is this how I would do it or do I need to do the
StartCoroutine(buttonClicked()); somehow?

leaden ice
thick socket
#

thanks ๐Ÿ™‚

mellow sigil
#

Yes, you need to start the coroutine normally even if it's in response to a button click

thick socket
#
MonoScriptImporterInspector.OnEnable must call base.OnEnable to avoid unexpected behaviour.
UnityEditor.Tilemaps.GridPaintPaletteClipboard:OnDisable () (at Library/PackageCache/com.unity.2d.tilemap@1.0.0/Editor/GridPaintPaletteClipboard.cs:347)
#

this error at all worrysome?

dusty badger
hasty haven
#

Technically yes, all the purchased items are technically permanent unlocks and i record your owned items in one place

leaden ice
dusty badger
hasty haven
#

Thats true, i mentioned i dont care about perfect security.
The save file is obfuscated to prevent simple text edits, it should also be relatively small for the scope of things

dusty badger
#

but similar idea maybe just adding some obfuscating calculations so the player can't find where the currency is

#

like some ratio or constant that always gets applied to the stored value

hasty haven
#

I just want to deter simple text edits and simple cheat engine edits on your money value

swift falcon
#

except my savesystem is trash

leaden ice
#

you'd have to obfuscate it in memory the way you do in the save file

#

And then use a property getter/setter to appropriately read/write the value as needed

hasty haven
#

Yeah im only using that value to display things on screen

#

So if you changed it it wouldnt matter, as long as you get the true value from the save itself right?

#

(when doing transactions)

dusty badger
#

so you would only store a value called A, and have a property of GetPrice function that returns A * obfuscating Ratio, and whenever you store the value you store A / obfuscatingRatio, A would have a name that they cant figure out what it's for

#

as a very simple example

leaden ice
#

I wouldn't use a ratio, rather something like a bit rotation cipher or something

swift falcon
#

I tried using multiple save system before, but that just backfired on me because i used playerprefs, but you can do better

leaden ice
hasty haven
#

Yeah i've learned a bit about encryption/obfuscation in some security classes

leaden ice
#

note none of this is going to prevent modification/cheating, it will just make it not work properly

#

the money amount will still change

hasty haven
#

Yeah if you mess things up it currently just slaps you with a fresh save file lol

leaden ice
#

it just won't change to the number they want

hasty haven
#

Okay, just trying to prevent average person from doing an easy edit.
Thats one thing that bugged me in risk of rain 2 is how easilly you can give yourself infinite currency or unlock challenges that are otherwise very challenging

leaden ice
#

I mean

#

you're only cheating yourself

#

you can cheat in solitaire too

hasty haven
#

This is true, theres no competitive edge in this game either.
You just have the fancy hat sooner than others

leaden ice
#

Why spend money on a game and then ruin the experience for yourself?

copper torrent
hasty haven
#

Thats sort of my teams mentality yeah

swift falcon
oblique spoke
hasty haven
#

GTA is a lot more sandboxy though, but yes lol

swift falcon
#

theres also caves of qud, that have debug in setting, they deliberately give the option to cheat, makes me feel not wanting to

delicate olive
#
    private float originalSprayInterval;
    private int originalSprayAmount;
    private float originalSprayBulletSpeed;

    private int originalBulletAmount;
    private float originalBulletSpeed;
    private float originalBulletInterval;
    private int originalBulletDamage;

    private float originalTimeBetweenActions;
    private float originalSpawnInterval;
    private float originalSpawnAmount;
    private float originalShootAmount;

    private void SetOriginals()
    {
        originalBulletAmount = shootAmount;
        originalBulletDamage = bulletDamage;
        originalBulletInterval = bulletInterval;
        originalBulletSpeed = bulletSpeed;
        originalShootAmount = shootAmount;
        originalSpawnAmount = spawnAmount;
        originalSpawnInterval = spawnInterval;
        originalSprayAmount = sprayAmount;
        originalSprayBulletSpeed = sprayBulletSpeed;
        originalSprayInterval = sprayInterval;
        originalTimeBetweenActions = timeBetweenActions;
    }

    IEnumerator UpdateAttributes()
    {
        scale = (float)atm.health / (float)atm.maxHealth;

        // Limit so that game doesn't become unplayable at very low health
        if (0.3f >= scale)
            scale = 0.3f;

        shootAmount = Mathf.RoundToInt(originalBulletAmount / scale);
        bulletDamage = Mathf.RoundToInt(originalBulletDamage / scale);
        bulletInterval = originalBulletInterval * scale;
        bulletSpeed = originalBulletSpeed / scale;
        shootAmount = Mathf.RoundToInt(originalShootAmount / scale);
        spawnAmount = Mathf.RoundToInt(originalSpawnAmount / scale);
        spawnInterval = originalSpawnInterval * scale;
        sprayAmount = Mathf.RoundToInt(originalSprayAmount / scale);
        sprayBulletSpeed = originalSprayBulletSpeed / scale;
        sprayInterval = originalSprayInterval * scale;
        timeBetweenActions = originalTimeBetweenActions * scale;

        yield return new WaitForSeconds(0.2f);
    }
#

Is there an easier way to do the above? I'm trying to make a boss fight where the different variables scale depending on the boss's health

copper torrent
delicate olive
#

This is long af so I don't want to keep doing this same thing over and over again if possible

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.

delicate olive
# rain minnow !code

Thought it wasn't too large because it didn't hit the Discord's text limit but ok

polar marten
#

what is your goal? what are you trying to do?

knotty sun
delicate olive
copper torrent
#

What am I doing wrong?

thick socket
polar marten
leaden ice
thick socket
#

I know how to jsom save/load but thats about it for saving stuff ๐Ÿ˜„

#

Just know there were an insane amount of options to try and pick from

vast matrix
#

Is there a way to disable Importing Assets programatically? I have a large function that writes thousands of files but it keps hung and interrupted by an import

stable rivet
#

how challenging is it to port an already existing point and click game to mobile (assuming the game is not too intense)?

i appreciate this is pretty dependant on how intense the game is - and i don't have anything to show - I'm just curious on whether or not it's an acceptable workflow to start a project targeting one platform, and (should the need arise) port to mobile down the line

copper torrent
polar marten
polar marten
stable rivet
#

that is music to my ears

polar marten
#

you will have a working, fairly playable game.

#

if you use Canvas to lay out your game, you will want to explore the different scaling settings.

copper torrent
polar marten
#

if you are using sprites, there are lots of good camera layout tools. cinemachine's are very good. even if your game is laid out with sprites

polar marten
stable rivet
#

does this extend to other parts of Event System also? i.e. OnDrag

copper torrent
#

no problem!

polar marten
#

if you used Event System, everything will just work

stable rivet
polar marten
#

if you use Input. somewhere, especially Input.mousePosition, you will want to change that. the best thing to do is to avoid Input. entirely. you can retrieve pointer data from the input modules. using Input System can also help, because ExtendedPointerEventData is more useful

stable rivet
#

yeah I don't plan on going back to the old input system

polar marten
#

then your thing is going to work very well

#

you can use the device simulator in the editor to test the different layouts easily

#

another valuable package is Notch Solution, which will give you UGUI components that help you lay out in response to the presence/absence of notches and rounded corners

#

i personally prefer to use physical canvas scaling and an aspect ratio fitter instead of the other scaling options, so that i can have better control over what should be website-style layout versus game content that is generally designed for a fixed aspect ratio*

#

but it may be redundant for your game

stable rivet
stable rivet
rustic rain
#

how would i save game data like xp and levels and stuff? would i use player prefs for that or save it in a json or something?

rain minnow
#

playerprefs should only be used for options or settings . . .

rustic rain
rain minnow
#

you'll find a plethora of tutorials online . . .

rustic rain
#

awesome, thank you

hollow stone
#

What's a good approach using interfaces on components? Considering that you may want to create dependencies in inspector and so on?
https://pastebin.com/p29ts8Bf Is there some better way than doing something like this?

polar marten
# hollow stone What's a good approach using interfaces on components? Considering that you may ...
class Switchable : MonoBehaviour {
  virtual void SwitchOn() {}
  virtual void SwitchOff() {}
}

// already exists. does not need to be modified
// door does NOT INHERIT switchable
class Door : MonoBehaviour {
 void Open() { ... }
 void Close() { ... }
}

// references door.
class DoorSwitchable : Switchable {
 [SerializeField] private Door door;
 override void SwitchOn() { door.Open(); }
 override void SwitchOff() { door.Close(); }
}

class DefaultBehaviourSwitchable : Switchable {
 [SerializeField] private Behaviour target;
 override void SwitchOn() { target.enabled = true; }
 override void SwitchOff() { target.enabled = false; }
}

class DefaultGameObjectSwitchable : Switchable {
 [SerializeField] private GameObject target;
 override void SwitchOn() { target.SetActive(true); }
 override void SwitchOff() { target.SetActive(false); }
}

class Switch : MonoBehaviour {
 public Switchable[] switchableObjects;
 ...
}
#

no need for interfaces

#

don't use them here

#

you might need some default behaviour for switchables

#

you'll be able to do it this way

hollow stone
#

Lets say hypothetically you wanted to implement more interfaces so you cannot go with inheritance?

polar marten
#

door does not inherit switchable

#

DoorSwitchable has a reference to a Door

#

@hollow stone do you see?

#

if you have more "interfaces" do the same pattern

hollow stone
#

My brain is computing, one sec^^

polar marten
#

it works in the inspector

#

you wanna add behaviors to doors? add behaviors to doors.

rustic rain
#

how would i check if guns are unlocked on a save file? i was just thinking that i could give each gun an ID from 0 to 6 for example, and then say like true, true, false, false etc

#

would this be a valid way to do it?

rustic rain
#

im doing that now

stable rivet
hollow stone
polar marten
#

if you want to add an aspect to a pre-existing component, write a new component and reference the existing one in it

polar marten
hollow stone
#

Aha ๐Ÿ˜… Figures.

polar marten
#

not because they don't make sense, but because in unity development you have full access to the source code, and you can modify nearly anything, so they are a worse option compared to alternatives

hollow stone
#

Lets say you have an input reader class instead, that you want to be able to mock. E.g.

    public interface IInputReader {
        public UnityEvent<Vector2> MousePressedEvent { get; }
    }
    public class GameInputReader : MonoBehaviour, IInputReader {
      ...
    }
    public class BoardStateMachine : MonoBehaviour {
        private IInputReader inputReader;
      ...
    }
polar marten
#

in my experience, when you have access to the source code, they are useful for things like

interface IReadOnlyValues {
 int value { get; }
}

class Something : IReadOnlyValues {
 [SerializeField] private int m_Value;
 override int value => m_Value;
 ...
 internal void SetValue(int inValue) => this.m_Value = inValue;
}

public void RenderValue(IReadOnlyValues hasValue) {
 // guaranteed to not modify the value of what was passed to it
 this.m_TextField.text = $"{hasValue.value} points";
}
hollow stone
#

Love the instant thumbs down x)

polar marten
hollow stone
#

How come?

polar marten
#
class InputReader : MonoBehaviour {
 public UnityEvent<Vector2> mousePressedEvent { virtual get; }
}
class Vector2UnityEvent : UnityEvent<Vector2> {}
class DefaultInputReader : InputReader {
 [SerializeField] private Vector2UnityEvent m_MousePressedEvent;
 public override UnityEvent<Vector2> mousePressedEvent => m_MousePressedEvent
}

public class BoardStateMachine : MonoBehaviour {
 [SerializeField] private InputReader m_InputReader;
}

@hollow stone now this can be edited in the inspector easily

#

i will also caution that this doesn't make sense. if you want to have au nified view of input, use input system

#

i don't think you're going to have more than one kind of input reader are you

#

you might even have only 2

#

you have full access to the source

#

based on how you are authoring this right now @hollow stone , you're going to be leaking details about reading input to the so called board state machine anyway

#

like a vector2 is not enough information

#

so

#

i don't know. give me a real example and i can show you

hollow stone
hollow stone
thick socket
#

How would yall do drop chance for items?

#

Just straight rand math seems hard if you want like 0.015% or other insanely low chance

hollow stone
#

Right now my ugly way of doing it is like this;

    public class BoardStateMachine : StateMachineBase {
        [SerializeField] private GameObject inputReaderObject;
        private IInputReader inputReader;

        private void OnValidate() {
            if (inputReaderObject != null && !inputReaderObject.TryGetComponent<IInputReader>(out _)) {
                inputReaderObject = null;
            }
        }

        private void Awake() {
            inputReader = inputReaderObject.GetComponent<IInputReader>();
        }
...
    }```
hollow stone
# polar marten what do you mean?

Lets say I would've implemented ICharacterInput and ICameraInput on on the same DefaultInputReader to be used in different aspects of the game.

ember cedar
#

How can i change this script so the gameobject doesnt spawn every frame

mild timber
#

I'm trying to set a boolean once a shake finishes with DOTween. The event never occurs though; isShake continues to be True.

transform.DOShakeScale(duration, strength).OnComplete(() => isShake = false);

#

does anyone know why the above code would not set isShake to false upon completion?\

astral blaze
#

i have a problem with these rotation camera scripts, it doesn't activate both script to make camera a rotation, but only one work. But how can i activate both script at same time?

cloud smelt
#

Wasnt sure which channel to put this in but does anyone know why setting the collider type seems to do nothing to my tiles? :

sacred frost
#

probably a mistake in the scripts

astral blaze
#

i dont think there is a mistake in the code

#

but i will share

formal bolt
dusk apex
sacred frost
#

do the debugs work?

astral blaze
#

yes

dusk apex
sacred frost
#

yeah well I think the rotations are just overriding each other

cloud smelt
#

@formal bolt Got it to work, had to fully restart the editor very strange

astral blaze
dusk apex
#

You need to evaluate using a single instance of current rotation.

thick socket
#

oof this line of code is long

dusk apex
#

!code

thick socket
#

wish I had coded this better early on ๐Ÿ˜ญ

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.

dusk apex
ember cedar
thick socket
dusk apex
dusk apex
#

Where the above would have your health member as private and instead provide a property to modify/read health.

#

Properties are simply methods under the hood but uses the same conventional format as the actual variable - note that value types are not accessed by reference but by value (similar to position, rotation and whatnot from the property members of the Unity Transform component).

#

You'd simply do cs player.Health -= damage;//Propertyrather than cs player.health -= damage;//fieldproperty being denoted with PascalCasing rather than camelCasing as it's simply a method under the hood - original Unity properties use camelCase but these were done so during the early years of Unity and would cause a lot of havoc if suddenly changed (or maybe they've got other reasons).

stiff tide
#

I have a question I'm not sure how to describe exactly, so I'm not sure what I would google.

I have an Xml file of cards (and card attributes). It is a list variable accessible from "deckXmlFile.mainDeck.Cards"

<cards>
    <card id="1" name="Test Name" pairName="Test Name Back"/>
    <card id="2" name="Second Card" pairName="Second Card Back"/>
    <card id="3" name="3rd test card" pairName="3rd test card back"/>
</cards>

If you only had one of the id numbers, for example id = "2". What's the best way find this line, or find the other attributes, such as the name?

I know I could make a method that ran a for loop, testing for the id. But is there a built in ability to do this? Something like
string card = deckXmlFile.mainDeck.Cards(id="2")

leaden ice
#

Depends how you're parsing the XML

#

If I was planning on accessing these by id a lot I would probably put them in a Dictionary after parsing the XML with the ID as the key

lone pagoda
#

Hey does anyone know why is this line highlighted?

#

I have the netcode package installed

thick socket
#

whats it say when you hover over it

lone pagoda
#

namespace netcode doesnt exist in the namespace unity

#

Nevermind I closed and reopened the project and it works fine

regal yarrow
#

Hey, how can I decrease the scale of a cube when I click on the corresponding side? (x side -> x-scale -=1)

leaden ice
rustic rain
#

how do i make it so the audio sources pause what theyre meant to play instead of stopping it fully?

leaden ice
rustic rain
#

currently theres a weird thing where if i pause while a clip is playing, the next clip that plays, both clips overlap each other

oak viper
#

when I access a transform via script (for example I print the name of its GameObject) it instead acts like its one of its children. I dont know why. It happens with a transform in the skeleton of my game character and just on some of them. Is this a bug?

#

anyone got an idea if this is a common mistake

leaden ice
#

You'd have to explain exactly what you mean

#

it instead acts like its one of its children.

#

what does this mean exactly?

oak viper
#

I access a transform in my hierarchy and I simply print out its name and it returns the name of one of its children.

#

if I print another transform it works as intended

leaden ice
#

How are you "accessing" it exactly?

oak viper
#

I saved the the transform in one of the components

leaden ice
#

show the the hierarchy, show the code, show the inspector, show the console, etc

oak viper
#

its hard to prove

leaden ice
#

Ok so what is GameManager

#

what is TPS

#

what is Torso

#

how are all these things assigned

#

it sounds like you've simply assigned something incorrectly

#

also when you print you should add some kind of label to it:

print($"Name of the torso is {GameManager.TPS.Torso.name}");```
#

Otherwise you may also be mixing up the log with a different one

#

This should be easy to prove, simply show all those fields, how they are assigned, etc.

oak viper
#

alright I will keep digging and come back with better prepatation if I dont find the mistake

#

found my mistake... forgive me for wasting your time. Wont happen again

wide dock
#

Yo, idk where to ask this but I'm making a 2D game and for some reason my player won't collide with the wall and will just go straight through it.
The wall is on UI layer, and the player is on Player layer, both have 2D colliders, non-trigger, player has a rigidbody and moves using MovePosition. In Physics2D settings the collision for UI/Player layers is checked.
What could be the problem here?

wide dock
rustic rain
#

how can i change sound effects based off what floor im on? so like wooden floors would make wood sound, stone would make stone etc. how can i make different tiles have different values?

fluid lily
#

Making a system and besides the numeris other better solutions I can't use because of unities super outdated C#, now this one has no work around as C# 11 has abstract static methods which is the only way for me to do what I want to do...

leaden ice
potent sleet
fluid lily
leaden ice
#

C# is turing complete

#

So by definition it's not the only way

rustic rain
#

can i have like an array of tiles that would all make the same sound?

#

so like a wood scriptable object orr something

potent sleet
rustic rain
#

how would the player know what tile it is on though?

#

sorry im askin a lot lol

potent sleet
rustic rain
fluid lily
leaden ice
#

But you haven't described your issue at all

#

So impossible to give you any advice

fluid lily
leaden ice
#

Then why did you post here lol

fluid lily
#

Your reply was just rude so I was being snarky

rustic rain
fluid lily
rustic rain
#

wait this is code general?

#

i thought it was beginner lmao

stable rivet
#

but you got pretty defensive immediately & if you don't actually need/want help then hey ho

#

GL

fluid lily
restive wyvern
#

what counts as code beginner and code general?

#

I assume it doesn't matter much but regardless

stable rivet
restive wyvern
#

I see

#

kind of

stable rivet
fluid lily
stable rivet
stable rivet
#

not here to argue - good luck with what you're trying to do

fluid lily
#

I said it is, they said they doubted my statement with no knowledge of my problem

unkempt sail
#

would there be a reason why Vector3.Angle() would always return 0?

#

even when its Vector3.Angle(Vector3.forward, Vector3.zero)

pearl otter
#

I am using the following code to jump, but if there is an object with a rigidbody on top of the player, the player barely jumps. The more objects I add on top of the player, the less the player jumps. I have tried setting the rigidbody mass to 0.0001 but it didn't help. Any ideas?

rb.velocity = new Vector2(rb.velocity.x, jumpForce);```
unkempt sail
#

use rb,AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse) instead

#

its agnostic to the current object's velocity and its surroundings

pearl otter
#

Same result

unkempt sail
#

well it would make sense why it would make it harder when its adding velocity to its self and the objects above it

#

why would there be other objects on top of the player

#

if its only one, and one only, or even more, I would just also add upwards velocity to the other objects on top of the player

pearl otter
#

The player controls multiple objects, its a puzzle game

unkempt sail
#

oh

#

then just give them also upwards velocity

#

does the puzzle involve the player balancing these objects on top?

stiff tide
#

I just started using dictionary variables for the first time, and I feel I'm lost on some basic understanding of how to use them.

I have a dictionary of keys. The keys are just strings of id numbers. "1", "2", etc. The values are small lists. Lists of two strings. I have a for loop adding these, and printing out what it's adding.

I'm trying to then access some of these values, and it's just not working. I've tried a bunch of things, one of them is commented out.

foreach (CardXml card in deckXmlFile.mainDeck.Cards)
        {
            currentDeckList.Add(card.id);
            tempNameList[0] = card.name; tempNameList[1] = card.pairName;
            Debug.Log("Added: '" + card.name + "' and '" + card.pairName + "' to the dictionary at Id key = " + card.id);
            try
            {
                cardNamesDictionary.Add(card.id, tempNameList);
            }
            catch
            {
                Debug.Log("Error importing the deck list. An element with Card Id: '" + card.id + "' already exists. Was it duplicated in the file?");
            }
        }
        Shuffle(currentDeckList);
        Debug.Log(currentDeckList[0] + ", " + currentDeckList[1] + ", " + currentDeckList[2]);
        //List<string> value = GetNamesFromId(currentDeckList[0]);
        List<string> value = cardNamesDictionary["3"];
        Debug.Log("Card Name: '" + value[0] + "', Card Pair Name: " + value[1]);
        value = GetNamesFromId(currentDeckList[1]);
        Debug.Log("Card Name: '" + value[0] + "', Card Pair Name: " + value[1]);
unkempt sail
#

if not, just freeze the all the objects

unkempt sail
#

make all the objects on top of the player not use gravity

#

if they're on top of the player

#

once the player lets them go, give them their normal gravity

stiff tide
pearl otter
#

Let me show you lol @unkempt sail, I explained it horribly. Give me a minute

unkempt sail
#

alr

pearl otter
unkempt sail
#

oh my

#

I made something just like this in a game jam like 5 months ago

pearl otter
#

Did you!?

#

This is for the Mini Jam 127

#

Theme: Catยฒ

unkempt sail
#

mine was controlling multiple players in a game called "you're a clone`

pearl otter
#

What a coincidence lol

unkempt sail
#

one of the puzzles involved a clone jumping on top of one of the other clones to get a jump boost

#

let me see what I did when they were on top of each other

lyric wadi
#

in my jump method I calculate the destination height of the jump and while the transform hasn't reached that height I add force upward

unkempt sail
#

yeah I just made the other players kinematic

#

but I don't think that would quite work since you're controlling all the enemies simultaneously

unkempt sail
lyric wadi
#

I'm using RB and addrelativeforce upward

pearl otter
#

Hmm

lyric wadi
#
        destinationY = transform.position.y + maxJumpyY;
        while (transform.position.y < destinationY)
        {
            _pcRig.AddRelativeForce((transform.up * trackSettings.JumpVelocity) * Time.deltaTime * 5, ForceMode.VelocityChange);
            yield return null;
         }
#

but that velocitychange mode might be off from what you're using, but it guarantees I always jump to that height

unkempt sail
#

its weird that all the objects don't jump together tho

stiff tide
unkempt sail
#

you're applying the same force to all of them, why wouldn't they just synchronously jump

unkempt sail
stiff tide
#

Wdym?

unkempt sail
#

moving from arrays and lists to dictionaries or hashsets can be tricky

stiff tide
#

I've been using lists a lot, those work just fine

unkempt sail
#

use a List<> instead of a Dictionary<>

stiff tide
#

I'm specifically trying to learn how dictionaries work

unkempt sail
#

then try your functions out using lists instead of dictionaries

#

oh

lyric wadi
#

like what is this supposed to be List<string> value = cardNamesDictionary["3"];

stiff tide
#
Dictionary<string, List<string>> cardNamesDictionary = new Dictionary<string, List<string>>();

The keys are strings, the values are lists of strings

lyric wadi
#

k so you are using it correctly

unkempt sail
#

if the key of the index is just a number why don't you use an int key instead?

lyric wadi
#

cardNamesDictionary.Add(card.id, tempNameList); isn't adding a string for card.id, guess card.id is a string of an int

stiff tide
unkempt sail
#

make the debug easier for your self

stiff tide
#

Alfy please stop. You are simply judging my style of coding and you are not helping.

lyric wadi
#

guess beginner might be better to ask in I'm not sure

stiff tide
#

There is a reason I'm using strings as the keys, they are just numbers right now.

unkempt sail
#

also string keys are much slower then int keys

stiff tide
#

omg stop alfy

lyric wadi
#

yeah it's fine I was just trying to follow along to verify you were doing it right

unkempt sail
#

nah I ain't stoppin

#

try debugging and adding a break point at the point where you're adding cards

#

maybe its just adding the same card over and over somehow

pearl otter
stiff tide
#

Alfy I have repeatedly asked you to stop being so rude, and simply judging what variable type I'm using. I'm calling in moderator help.

lyric wadi
#

Trae, just trying to understand the problem, you're saying cardNamesDictionary["3"]; debugs out the wrong card?

stiff tide
#

Yes

unkempt sail
#

dude, I just told you to add a break point in the code

#

please call me a mod

pearl otter
#

That works ๐Ÿ˜„

unkempt sail
#

there you go

#

just don't make it so that players identify each other as ground

#

that could make some problems later

#

try making a different var like onOtherPlayer

pearl otter
unkempt sail
#

good job

pearl otter
#

How should I fix this

unkempt sail
#

?

#

oh

#

uh

pearl otter
#

It is detecting the same cat as a cat under it so it can jump in air

sacred frost
pearl otter
#

Why do people use Physics2D.OverlapCircle to check for ground instead of raycast?

unkempt sail
#

how are you making the player jump?

#

as in input?

sacred frost
pearl otter
#

Yep

pearl otter
potent sleet
#

cause there is a better chance to detect ground with a circle instead of a line

pearl otter
#

I see

unkempt sail
#

some people still use a specified collider for ground detection

pearl otter
#

Can Physics2D.OverlapCircle tell me the object it overlaps?

unkempt sail
#

yes

#

it returns a Collider

pearl otter
#

Ohh it clearly says Collider2D facepalm lol

unkempt sail
#

and even a List of them if you want multiple

lyric wadi
#

i do raycasts cause I have a different animation if you're above a certain height during a jump (glide vs landing anim)

pearl otter
potent sleet
#

it returns an array of colliders

unkempt sail
pearl otter
#

Thanks

potent sleet
unkempt sail
#

I like to use the explicit declaration because confusion

unkempt sail
pearl otter
#
        Collider2D[] collider = Physics2D.OverlapCircleAll(groundCheck.transform.position, 0.2f, collidableLayer);
        for (int i = 0; i < collider.Length; i++)
            if (collider[i].gameObject != gameObject)
                return true;
        return false;```
This fixed it ๐Ÿ™‚
lyric wadi
#

think they need to debug.log card.id when they add it to the dictionary as well, verify it's what they think because cardNamesDictionary["3"] is giving a different card than they're expecting

pale owl
#
    {
        BGM.clip = music;

        if (BGM.clip != music)
        {
            BGM.Stop();
            BGM.clip = music;
            BGM.Play();
        }

    }

The above is in my Audio Manager

    {
        if (BGM.clip == music)
        {
            return;
        }
        BGM.Stop();
        BGM.clip = music;
        BGM.Play();

    }

Or alternatively even this above one could be my audio Manager. (Both dont work)


    private AudioManager theAM;

    public void Awake()
    {
        theAM = FindObjectOfType<AudioManager>();

        if (newTrack != null)
        {
            theAM.SwitchMusic(newTrack);
        }
    }

This is in my music script

The Audio Manager also doesnt destroy on load. Does anyone know why this wouldnt play the music from my Music object, in the Audio Manager's BGM.clip?

I had a different code before but it wasnt working, so I changed it because it was just too confusing for me. Now this new code also isnt working. I'm very confused why. Its been days that I've been working on this.

potent sleet
sacred frost
# pale owl ```public void SwitchMusic(AudioClip music) { BGM.clip = music; ...

how about

[SerializeField] private AudioSource backgroundMusic;

public static AudioManager Instance { get; private set; }

private void Awake() {
  Instance = this;
}

public void SwitchMusic(AudioClip musicClip) {
  backgroundMusic.clip = musicClip;
  backgroundMusic.Play();
}

for the second

public AudioClip newTrack;

    public void Start()
    {
        if (newTrack != null)
        {
            AudioManager.Instance.SwitchMusic(newTrack);
        }
    }
pale owl
#

I'll try that.

Thank you!

pale owl
unkempt sail
#

try looping the audio source

pale owl
#

OH!!!

#

I FIXED IT

#

ITS BEEN 3 DAYS

#

I FINALLY GOT IT WORKING!!!

sacred frost
#

np

unkempt sail
#

good job

wintry grove
#

(damn just asked a question in another chat but I'm getting to parts of my game where I'm a bit lost in haha)

So I've seen it's not very good to make your world go to high numbers as higher out, the more incorrect calculations happen or something..

How do people tend to deal with that? Using some sort of world streaming system?

#

My world is going to be large (as it's going to simulate a star system) so I'm wondering if I should have a world streaming system and every warp would kinda have the illusion you're moving but you aren't.

Not sure how people go about this tho

unkempt sail
#

outer worlds made the world move around the player somehow instead of the other way around

wintry grove
#

That is crazy lol

lyric wadi
#

yeah for super massive scenes they move the environment and the camera stays at origin

wintry grove
#

My game has the benefit where you'll mainly be warping to travel to far out areas

lyric wadi
#

then you could just launch another scene you warp to and reset the origin

wintry grove
#

I would but 100 star systems + up to 8 or 9 scenes per system seems overkill haha

unkempt sail
#

maybe try making everything 10x smaller?

#

lets say that the biggest object would be at scale 1

#

and everything else would be comparatively smaller

formal bolt
wintry grove
formal bolt
wintry grove
#

Someone did bring that up to me

formal bolt
#

realistically you shoudl not have an ovject that is 10k miles away loaded at any times anyway

wintry grove
#

When you move into the next grid does it move you back to 0,0,0

formal bolt
#

so you need a definition of "position" that is different from unity's world space

wintry grove
#

Ahhh gotcha gotcha

#

So like my own internal coordinate system

formal bolt
#

yeah

wintry grove
#

So instead of chunks I could handle it via "warps". And just load the grid around the warp each time. Then when I warp to another location I can poof you to that warp's area etc.

unkempt sail
#

it would be sick if unity started using doubles instead of floats

wintry grove
#

I read about that. But it introduces performance issues iirc

formal bolt
#

there's lots of benefits to floats, but its getting less over time

#

unity was built on float bostly because of device limitations at the time

wintry grove
#

Ahh yeah that's true

formal bolt
#

but there's lots of ways to work around it, and really, your world "model" should not be calculating positions based on unity's definition of worldspace

#

unless your'e working onf a very small scale

unkempt sail
#

I guess switching to doubles would probably take a bunch of time to change everything to support doubles

#

specially the rendering

wintry grove
#

It's my first time experimenting with large scale worlds but I'm basically doing this as a huge programming challenge lol

unkempt sail
#

not like its a find a replace operation

wintry grove
#

I like eve but I wished it were single player and therefore my project exists lol

formal bolt
#

@wintry grove what scale are you workign on like universe scale, planet scale

#

how big do numbers get

wintry grove
#

I assume you meant to talk to me?

#

XD

formal bolt
#

omg lol

#

i fixed xD

wintry grove
#

Planet scale if we're talking about warps. Like huge planets in the background.

#

With the ability to warp around the star system

formal bolt
#

so sclae of like millions of kilometers

#

and how finite

wintry grove
#

So basically illusion to fade in / contort time then poof to next station

#

What do you mean in regards to finite?

formal bolt
#

like how small scale

#

can you land on planets

wintry grove
#

Oh no

formal bolt
#

can you shrink to ant size

wintry grove
#

Its entirely in space

formal bolt
#

okok

wintry grove
#

So it's easy in that regard

#

The ships will be the smallest things

#

And planets will be nothing more than skybox illusions

formal bolt
#

it sounds like you want like 2 scenes, one for space and then a separate scene for each ship

#

and the scale on each scene is very different

#

are you familiar with LOD

wintry grove
#

What would the purpose be of ship specific scenes?

#

I'm planning on fleets btw not just individual ships

formal bolt
#

well, you can make one scene the entire space at low detail, so maybe 1000 units across in unity units

#

but then make a ship also 1000 unity across in unity units, but obviously you experience it differently

#

so different scene can define the sence of scale

wintry grove
#

Are you meaning something similar to this?

formal bolt
#

yes similar, except a skybox is never part of the world

#

if you want to be able to visit and fly around planets and moons you would need to do somethign a bit trickier

wintry grove
#

Ahh. I wouldn't intend for that

#

I'm keeping eve's style where the planets and moons are visible and large

#

But never more than something in the distance

formal bolt
#

well then yes a skybox is perfect

#

you just want a giant open area in space to fly around in?

wintry grove
#

Basically.

#

There will be combat, mining, etc

formal bolt
#

ok yeah, then that videowould explain how to do wha tyou want perfectly

wintry grove
#

But it'll all be done in space

formal bolt
#

skybox is goo because you can make it very details with a very small scale map

wintry grove
#

Yup. It's very good for making illusions

formal bolt
#

yes

wintry grove
#

Appreciate the talk I have a more direct approach on how to tackle this haha

formal bolt
wintry grove
#

I still have to figure out simulating AI ships doing things when they aren't loaded XD

#

Oh yeah LODs

#

Further away = less rendered right

#

Up close = more detail

formal bolt
#

you have different meshes that will swap out when things move in and out of range

wintry grove
#

Ahh gotcha gotcha

formal bolt
#

for anything you can ac tually get close to liek other ships or asteroids, it's good to do

wintry grove
#

Gotcha. Yes that would be perfect to learn I'll bookmark this

#

Appreciate the talk! I have a more direct understanding of this now

pearl trench
#

how can I check if a collider is colliding with another collider? none of them have rigid bodys

west knot
#

OnCollisionEnter

lyric wadi
#

needs rigidbody for any of the collision callbacks

west knot
#

you can't detect collision without a rigidbody? I thought you only needed that for physics

lyric wadi
#

OnCollisionEnter/OntriggerEnter need rigidbody to fire

#

Note: Both GameObjects must contain a Collider component. One must have Collider.isTrigger enabled, and contain a Rigidbody. If both GameObjects have Collider.isTrigger enabled, no collision happens. The same applies when both GameObjects do not have a Rigidbody component.

west knot
#

i guess i've just never done that. Good to know

lyric wadi
#

it's common people asking why it's not working and it's because they don't have a rb

clever mulch
#

And later on you can just refer to the last table ๐Ÿ™‚

ocean pewter
#

Anyone got any experience using Microsoft.Data.SQLite.Core or the custom SQLite PCL bundles from UnityNuget?

#

just wondering if you can use one of the bundles with Microsoft.Data.Sqlite.Core, like SQLitePCLRaw.bundle_e_sqlite3 since it says it doesn't include the native library with it, or if you just include the library in the plugins folder for unity to pick it up

placid ridge
#

Hi there!

I'm having trouble with my editor preview system. Whenever i set a color on the same sprite on a custom tile the colors merge I have provided in the video what is happening, here is my script:

using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.Tilemaps;


[CustomEditor(typeof(LevelTile))]
public class LevelTileEditor : Editor
{
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();
    }

    public override Texture2D RenderStaticPreview(string assetPath, Object[] subAssets, int width, int height)
    {
        Tile Target = (Tile)target;
        if (Target.sprite != null)
        {
            Texture2D newIcon = new Texture2D(width, height);
            Texture2D spritePreview = AssetPreview.GetAssetPreview(Target.sprite);
            Color[] pixels = spritePreview.GetPixels();
            for (int i = 0; i < pixels.Length; i++)
            {
                pixels[i] = pixels[i] * Target.color; // Tint
            }
            spritePreview.SetPixels(pixels);
            spritePreview.Apply();
            EditorUtility.CopySerialized(spritePreview, newIcon);
            EditorUtility.SetDirty(Target);
            return newIcon;
        }
        return base.RenderStaticPreview(assetPath, subAssets, width, height);
    }
}

Thanks!

vale gyro
elder flax
#

whats the best way to handle a ton of rigidbody items

#

i have a script that turns off the rigidbody if it gets too far from the player

#

but it checks distance on update and i suspect its losing more performance than it saves

#

i could give them all unity LOD but i cant really because LOD group doesnt support multi object editing for some reason

edgy lynx
elder flax
#

nope

#

i am pretty sure that my script thing is the biggest performance drain

wispy wolf
#

make sure you are using square magnitude instead of magnitude when checking distance. sqrts are expensive

edgy lynx
# elder flax nope

No point in guessing. Hundreds of RBs should really be fine. Profile and see if you actually need to do any optimizations. Majority of the time reducing polygons, light baking, etc. will have a much higher impact on performance than the code. I would start there first.

#

But the definitive answer is: Profile.

elder flax
wispy wolf
#

That just calls (a-b).magnitude, which has to do a sqrt because that's how math works. Just do (a-b).sqrMagnitude

#

Then check that against your distance threshold^2

#

But also just profile it

elder flax
#

yeah im on it

lusty hollow
#

So there's an Application.persistentDataPath, as well as an Application.temporaryCachePath. Is the CachePath cleared when you exit or something? Or what's the deal with that?

#

We create a directory path where temporary data can be stored, but how temporary is that?

wispy wolf
#

@lusty hollow I don't think there is a clear answer on that. If you have data that can be temporary I'd probably just put it a tmp dir in the persistentDataPath and delete it when the game starts and exits.

lusty hollow
wispy wolf
#

If you want to use temporaryCachePath I'd be cautious and never assume that something is there, even if you just wrote to it

unique cloak
#

Hey I tried some googling but I couldn't find a simple way to word this question that would yield an answer. I have a class with some properties and a List of objects in that class. I'm wondering, is there a way to iterate through each item of that list and see if any of the objects of that class have a property equal to some value I designate? i.e. something like the pseudo code below

list objects;
bool objects_property_contains_number_5 = objects.property.Contains(5);
return(bool)

to tell me whether any of the objects in my list have some property "property" = 5

west knot
#

for loop

unique cloak
#

yea without going through each value individually

#

like some inbuilt function to check the properties of a list

west knot
#

?

#

but that loops through all the items as well

unique cloak
#

right

west knot
#

you don't have to make the loop though

unique cloak
#

so might aswell just use a for loop

#

yea ok cheers

west knot
#

i don't think there is anyway around looping through the list

unique cloak
#

yea well I wanted to avoid that cause optimisation but I guess I can just loop through and break when I find it

#

sorry not thinking clearly today

west knot
#

there is also List.Find that will find the first one in the list

unique cloak
#

ty

west knot
#

how big is the list?

kind grove
#

LINQ should help you

west knot
#

any time you query the list it is going to loop through the list right? He wanted to avoid looping the list for some reason.

leaden ice
#

For example a Dictionary

#

Your original question is pretty vague though, and seems contrived with this number 5 thing

maiden inlet
#

How do i get concrete types of generic Types by reflection?
For example i want to find all concrete MyClass<T> Types like MyClass<int>, MyClass<float> etc...
assembly.GetTypes() will only get me something like "MyClass'1"

#

is it even possible?

mossy snow
#

MakeGenericType

maiden inlet
#

i dont need to make them. i need to find all Types defined in the assembly to display them in a dropdown in the editor

mossy snow
#

oh, misread. Why not use IsSubclassOf? should be something along the lines of assembly.GetTypes().Where(ti => ti.IsSubclassOf(typeof(MyClass<>));

#

if it's editor only, you maybe want to use TypeCache.GetTypesDerivedFrom instead of assembly.GetTypes(), I'm not 100% sure it works with an open generic type though since I've never tried it for that purpose