#💻┃code-beginner

1 messages · Page 837 of 1

wicked stratus
#

I did not know this!

#

For some reason, raycasts have been intimidating to me so I've sort of been avoiding them

sour fulcrum
#

raycasts are super simple and will be a very common tool in your toolkit

wicked stratus
woeful coyote
#

See video below
My camera is 'snapping' when I try to move it. Previously, when I referenced the camera, I used camera for the variable name. I changed it to cam due to console warnings, but now I get this issue. I have ruled out multi-script conflict. What is happening? I'm new to this.

Here's the script, it's kind of short

public Camera cam;
    private float xRotation = 0f;

    public float xSensitivity = 30f;
    public float ySensitivity = 30f;

    public void processLook(Vector2 input)
    {
        float mouseX = input.x;
        float mouseY = input.y;

        // Calculate UP and DOWN
        xRotation -= (mouseY * Time.deltaTime) * ySensitivity;
        xRotation = Mathf.Clamp(xRotation, -80f, 80f);

        // Apply to camera transform
        cam.transform.localRotation = Quaternion.Euler(xRotation, 0, 0);

        // Transform for LEFT and RIGHT
        transform.Rotate(Vector3.up * (mouseX * Time.deltaTime) * xSensitivity);
    }
#

I just realized it may not be noticeable, but the camera does not move smoothly, it snaps to places when looking around

woeful coyote
#

Sorry for the code wall

narrow idol
#

hello which channel can i ask for general help in?

woeful coyote
woeful coyote
narrow idol
naive pawn
#

mouse delta is already a delta, already per frame

woeful coyote
naive pawn
#

yeah

#

you'll have to reduce the sensitivity to compensate

#

not sure it's the issue here, but definitely an issue

woeful coyote
#

Works as expected, thanks!
Strangely the tutorial I was following used delta and it worked, but the look works for me now

#

Thanks again

naive pawn
prisma shard
#

Sometimes I dump my entire game code into an AI to scan for any bugs I might have made. Am I wrong to be paranoid of doing this with Chinese models? Like I want to see how good they are at debugging in comparison to stuff like OpenAI and Claude but i have no idea what they might do with the code because they likely are much less afraid of being sued

naive pawn
#

paranoid for what?

prisma shard
#

Of them eventually stealing it and making a duplicate game if it got advanced far enough

naive pawn
#

i don't think business practices are much different for any of the genAI as a service companies

naive pawn
sour fulcrum
#

I don't think paranoia about a specific country potentially doing something with data your providing them is suitable for this server tbh

naive pawn
#

they aren't sifting through all the input for the 0.001% that happens to be game code

prisma shard
#

Idk I just know how good even an dated agency like the FBI is at keyword searching through the internet. Maybe they have a way to find coherent holistic codes from doing the same

naive pawn
#

they do

#

they just aren't

#

because that's not economically viable

#

if they want to make money doing shady things, there are more lucrative ways to use the data

prisma shard
#

Obviously no indie game would be cyberpunk but if someone dumped the entire code of cyberpunk 2077 into Qwen 6 months before the game released, u dont think there is any danger of doing that?

naive pawn
#

no

#

well there is danger of you getting sued because you broke NDA, probably

#

i don't know what qwen is, but assuming they're a typical chatbot company with a ton of traffic, they aren't sifting through the traffic for code to steal

#

especially given that a) they wouldn't know it's there to begin with, b) it wouldn't be contiguous, c) they wouldn't have the assets and infrastructure to build and publish the game anyways, d) they don't have the marketing to make it an attractive financial choice

prisma shard
#

Maybe im thinking of stealing code wrong when i heard it used. Because i always hear people saying google and openai is making money off of stolen code and im not entirely sure what that means

naive pawn
#

they aren't just republishing the code as-is

sour fulcrum
naive pawn
brisk robin
#

(Sorry, don't mean to interrupt the conversation, just want to get this question out.) When "leaningin" is false, I want the game to change the parent of "opptextbox" to be the new canvas and resize it. My understanding of my If statements here is that, if the parent ISN'T oppcanvas, then frame 1, the update function should run the stuff I commented "frame 1," then on the next update frame, it should run the "frame 2" section. Am I understanding the update function properly?

prisma shard
#

If you are implying someone is going to decompile it, i will assure that doesnt happen xd

naive pawn
#

the only 100% assurance is not publishing it to begin with

prisma shard
#

Ill be honest i really only ever hear of godot code being decompiled.

sour fulcrum
#

most unity codes are decompilable

#

anything compiled with mono

sour fulcrum
#

I have witnessed first hand multiple newbie modders for unity games dump a compiled game right into an ai assistant not knowing thats not ok

naive pawn
#

to publish the game, you need to publish the instructions for how the game works. the instructions can be extracted, and then reversed into what they couldve been in the source code

prisma shard
#

wait wtf, isnt hearthstone literally a unity game

#

and genshin

naive pawn
sour fulcrum
#

also in the future post your code via

prisma shard
sour fulcrum
#

!code

radiant voidBOT
ivory bobcat
naive pawn
#

note that i did not say reverse engineering

#

i just said reverse

brisk robin
prisma shard
#

Does it count as decompiling if i am analyzing the behavior of a famous game and duplicating the behavior into my game

brisk robin
#

The issue I'm having is a flash of white due to the text staying really big relative to the new canvas. Like, the letters are taking up the whole screen. I don't see why they WOULD, if I'm disabling the textbox and making the text smaller on one frame, then turning the textbox back on on the next frame

naive pawn
naive pawn
#

depending on how charitable you want to be and how close you're going

brisk robin
naive pawn
#

ah ok

#

(if you want help with that you'll probably have to give some more context and show hierarchy setup, also see https://xyproblem.info )

brisk robin
#

Well, knowing that I understand the update function running those on two separate frames was a big help. I just wanted to make sure I'm not crazy. I have other ideas for potential solutions, just wanted to make sure I understood that part for troubleshooting

sage mirage
#

Hey, guys! There is a problem I have with references when changing scenes, basically I want to assign references at runtime when changing a scene and using DDOL for specific singletons I have. I have heard about Service Locator Pattern & Dependency Injection. Could you please help me understand what they do like the logic and also what are the pros and cons and whatever?

ivory bobcat
#

These patterns aren't unity specific

obtuse hollow
#

I mean, it depends on what you want to do. If I have singletons, then I just make a container class, with statics to those classes that are singletons, and just acess them whenever I need, without creating any references in non singleton classes.

#

But I dont have to care about any safety and "pretty" code since im solo so im doing whatever I want lol

sage mirage
#

I dont think you are experienced enough then

sage mirage
#

If you dont think about refactoring and better optimization techniques etc then you are not good at programming and not experienced

#

I always think about better architecture etc

obtuse hollow
#

Not really, my code is pretty performant and im quite good at programming, the thing is that if you are solo, you can do whatever you want, no reason to do boilerplate code, keeping things simple always beats complex solutions if they are not sucking up performance

sage mirage
#

Its not about writing code we can all write code the hardest part is how you connect everything and making a clean architecture. So, my point of view is recognizing which pattern is most effective on a specific software design issue you have as a programmer and actually understanding which Data Structure is better to use for a specific problem because this all has to do with Time & Space Complexity at the end of the day if you dont care about all of that then you dont care about your code and if you dont care about your code you will have many issues because when the project is getting bigger and bigger you wont be able to maintain XD

sour fulcrum
#

they didn't ask

sage mirage
#

The point is you have to always apply best practices even as a solo because if you apply them as a solo dev you will be able to apply them with a team as well

#

I dont have to wait until I start my work at a company or a team in order to learn Github. I am learning Github even as a Solo Dev because I want to learn the Workflow and get more experience handling merge conflicts and versioning my code its the same thing on this one we are talking about.

obtuse hollow
#

Aside from the fact that I dont intend to bring any other programmer to the projects (so I might bring someone from graphics for example), ignoring stiff patterns doesnt mean forgetting about optimizations. It means doing stuff with common sense. Most of the time Im doing patterns without even knowing it, but I do not care if I do them or when I should apply them. Ease of use first if the code is not performance critical, performance over anything else otherwise.

sage mirage
#

Ok anyway my question was about DI and Service Locator Pattern

obtuse hollow
#

And I anwsered you how I do things, and you tried to do... I am not sure what exactly

sage mirage
#

But like the other guy said this is not Unity Specific maybe I have to ask it in programming server

sage mirage
#

I want to understand the DI and Service Locator so probably I am gonna ask and search for them

twin cloak
# sage mirage Ok anyway my question was about DI and Service Locator Pattern

I think both of them are really good but from my experience different people handle better different solutions.

I am personally more of a DI guy,
So in my unity project I have one single entry point and that is giving control to everything, including every manager and systems that are relevant to the pillars of the game or whatever you wanna call it
so all my systems and different parts of the game already know each other from the very beginning.

in most multiplayer systems they use a service locator, which is quite a different pattern,
in my own systems I don't use a service locator because I already have one main entry point which tells everyone which reference to get,
but I can still work with reference locators of other systems.

The only way for you to know which one you like most is to just try each and eventually see which you like more

#

the general appraoch in unity is to expose references in each script where you need, and manually assign through the editor.
Only use these for stuff you know you can't get through the editor or have a good reason for

sage mirage
#

So I am assigning references I need at runtime

#

when the scene transition happens in awake if I am not wrong

ionic zealot
sage mirage
#

Hey, guys! If I want to stop a coroutine within a coroutine I have to do something like

#
{
    while (true)
    {
        if (GameManager.Instance.CurrentGameState != GameState.Playing) StopCoroutine(SpawnLivesDelay());

        yield return new WaitForSeconds(spawnLivesDelay);
        SpawnLivesAtRandomPoints();
        yield return new WaitForSeconds(spawnLivesDelay);
        ObjectPoolManager.Instance.ReturnObject(LIVE_TAG, SpawnLivesAtRandomPoints());
    }
}```
#

because it doesn't allow to use return within a coroutine

#

So, I can just use StopCoroutine right?

ivory bobcat
ivory bobcat
#

And you'd want the coroutine instance, not the coroutine function (if you're really wanting to stop it)

naive pawn
#

(but yeah you can just break the loop if it's on a loop)

sage mirage
#

oh yield break I will keep it in mind

cosmic dagger
sage mirage
#
{
    int rand = Random.Range(0, 6);
    GameObject live = ObjectPoolManager.Instance.GetObject(LIVE_TAG);
    live.transform.position = spawnLivePoints[rand].transform.position;
    return live;
}

public void SpawnEnemiesAtRandomPoints()
{
    int rand = Random.Range(0, availablePoints.Count);
    GameObject enemy = ObjectPoolManager.Instance.GetObject(ENEMY_TAG);
    enemy.transform.position = availablePoints[rand].position;
    enemiesAlive++;
    availablePoints.RemoveAt(rand);
}

public int EnemiesToSpawn(int wave)
{
    int enemies = 1 + wave / 3;
    if (enemies > 4) enemies = 4;
    return enemies;
}

public IEnumerator SpawnLivesDelay()
{
    while (true)
    {
        if (GameManager.Instance.CurrentGameState != GameState.Playing) break;

        yield return new WaitForSeconds(spawnLivesDelay);
        SpawnLivesAtRandomPoints();
        yield return new WaitForSeconds(spawnLivesDelay);
        ObjectPoolManager.Instance.ReturnObject(LIVE_TAG, SpawnLivesAtRandomPoints());
        yield return new WaitForSeconds(spawnLivesDelay);
    }
}```
Now, I have another issue. If you can help me figure it out maybe. So, the problem is that my power up doesn't disappear after the X seconds so the power appears and then after X seconds doesn't disappear.
#

On my SpawnLivesDelay() coroutine there is a problem and I dont get any errors.

#

Oh

#

The problem probably is that I dont store the reference to a variable when returning the value from the method

#

@ivory bobcat Why you erased your reply message?

naive pawn
#

if you want to return a GO that has previously been allocated, you need to have a variable for it, and then return that

ivory bobcat
#

I misread. I thought that the problem was solved..

  • Verify the delay value
  • Make sure that the despawn instruction is called
  • Make sure that what's being despawned is the correct object
sage mirage
#

it was solved

#

The problem was that I didn't store the reference to a variable

ivory bobcat
#

You should cache the spawned object before the second wait statement and despawn that object instead some other new random object

sage mirage
#
{
    while (true)
    {
        if (GameManager.Instance.CurrentGameState != GameState.Playing) break;

        yield return new WaitForSeconds(spawnLivesDelay);
        GameObject live = SpawnLivesAtRandomPoints();
        yield return new WaitForSeconds(spawnLivesDelay);
        ObjectPoolManager.Instance.ReturnObject(LIVE_TAG, live);
    }```
#

Thanks for the help btw !

twin cloak
naive pawn
sage mirage
#

The problem is I dont want to touch right now anything because I dont want to break my code

twin cloak
#

what do you mean

sage mirage
#

and my project basically because I have chosen to create bridges and actualyl assign references I need manually

twin cloak
#

I think I don't understand what is the issue that you are trying to solve with these patterns

sage mirage
#

I am sure you dont understand

#

It's dependency + references + scene transition issue

#

because I have managers on my first scene

#

an d I want to assign references I hve on my other scenes

#

and I use DDOL and bridges like I said to do so

#

its not an issue basically

#

its just about better maintainability and flexibility

#

Its not a problem I can continue working with this method

#

How I am supposed to help you understand?

#

Just guide me

#

Can I provide 3-4 important scripts I have there TitleSceneBridge, MaiNSceneBridge and 2 others maybe

#

I want you to see and unerstand

#

understand

sage mirage
#

public void RaiseDecreaseLivesUI() => OnDecreaseLivesUI?.Invoke(playerHealth.PlayerLives, playerHealth.CurrentLives);

#

I have to pass arguments to my Invoke if I have arguments on my method I want to invoke?

opal minnow
#

im having trouble with the xri button inputs, the grips, triggers, and joyssticks all have their own input action but the primary and secondary buttons do not. Is there something I am missing or do i have to manually assign these.

grand snow
#

any old class can be used for this but if you are having issues with dependency management perhaps a DI framework or your own DI system may help

misty sand
#
    {
        if (ceilingLightMaterial != null)
        {
            ceilingLightMaterial.SetColor("_EmissiveColor",
                on ? emissionColor : Color.black);
        }

        if (corridorCeilingMaterial != null)
        {
            corridorCeilingMaterial.SetColor("_EmissiveColor",
                on ? corridorEmissionColor : Color.black);
        }
    }``` I cant figure out why my emission materials for the corridor wont change to black like the main ones do when they should
#

i cant put the full code in

timber tide
#

Is this a reference problem or more of a rendering problem

#

if reference problem, understand what the sharedmaterial property is on your renderers

misty sand
#

to be honest i couldnt tell you, im not too sure.

wintry quarry
feral scaffold
#

how i can verify the ration of white/black in a render texture?

wintry quarry
#

Are you trying to figure out how "bright" the image is?

feral scaffold
#

no my render texture is used for a mask in a shader and i want to know how much of the render texture is erase

green osprey
#

what do i dod to make image 2 look like image 1

radiant voidBOT
cosmic dagger
radiant voidBOT
rich adder
#

double kill

cosmic dagger
#

tsk, 2nd place . . .

green osprey
#

im confused

wintry quarry
feral scaffold
rich adder
green osprey
wintry quarry
rich adder
#

if its not working like image 1 then its not

feral scaffold
rich adder
feral scaffold
feral scaffold
#

can you explain how it's work or it's too complicated

wintry quarry
# feral scaffold can you explain how it's work or it's too complicated

e.g.

AsyncGPUReadback.Request(myRenderTexture, 0, request =>
{
    if (request.hasError)
    {
        Debug.LogError("GPU Readback error occurred.");
        return;
    }

    // Get the data as a NativeArray for high performance
    var pixelData = request.GetData<Color32>();

    int numberOfWhitePixels;
    // Iterate over the pixels
    for (int i = 0; i < pixelData.Length; i++)
    {
        Color32 pixel = pixelData[i];
        if (pixel == Color.white) {
          numberOfWhitePixels++;
        }
    }
});
fading marten
#

Does anyone know what happened? My Unity project just reverted its scenes back to a few weeks ago and all of my work in that scene got erased

wintry quarry
feral scaffold
wintry quarry
wintry quarry
wintry quarry
feral scaffold
fading marten
#

I made another scene today, then when I went back to the other one that one was reverted

wintry quarry
wintry quarry
#

Stop using OneDrive and switch to a proper version control system.

fading marten
#

ok hang on, I made a demo version of the game and that one is saved

#

am I able to edit that demo version?

solar hill
#

if you have the project itself and not just the game then yes

fading marten
#

I have the build

#

can I edit the build?

sour fulcrum
#

no

wintry quarry
#

you mean asset rippers? Probably. It's against the rules of this server to really talk about them. But that's a really silly thing to even think about for your own project

rich adder
#

You can decompile a binary but it won't be the same or guaranteed to do so

sour fulcrum
#

in most cases it's more trouble than it's worth

wintry quarry
#

yeah you will spend more time trying to sort out the spaghetti mess it gives you than just redoing your scene.

rich adder
#

take it as a hard lesson into using a proper version control from now on and ditch that malware called microshit onedrive

fading marten
#

but how can it change just from going to a different scene?

wintry quarry
fading marten
wintry quarry
#

why don't you check the history of the file in OneDrive?

#

Doesn't OneDrive maintain file history?

fading marten
#

I didn't even know it was in OneDrive

#

it was apparently in my personal section

#

I don't know how to check fileHistory

feral scaffold
feral scaffold
wintry quarry
#

Do whatever you want with it

#

call a function

#

like make a function that takes the percentage and decides whether to activate or deactivate the object

#

and call that

fading marten
#

hang on, hang on

#

I don't see version history when I right click it

feral scaffold
fading marten
#

God damn it, it only says April 6th

midnight tree
#

Architecture questions

toxic spoke
#

how to make cube explode into a million pieces

rich adder
#

or you need to make it pre-cut yourself and have 2 versions

midnight tree
#

||Create the million pieces that fly apart from the explosion||

rich adder
#

You can fake it also using things like VIsual Effects graph

#

it really depends on the usecase

toxic spoke
#

what if i make a million cubes and then make a rigid body explosion

rich adder
#

thats a way to do it sure

#

essentially 3 ways.. not including generative ones like voxel and mesh deforming algos
pre-fracture (most common)
fake it with many cubes
or simulate it with particles

toxic spoke
#

or put a boom texture on it and then seperate it to a million pieces

midnight tree
#

If you make a million cubes, there will be huge problems with optimization.

toxic spoke
#

then connect 200 playstation 3's together

rich adder
#

at the end of the day it comes down what performance cost you're willing to tolerate for the endgoal.
in most cases the player wont care (if doesnt affect performance)

real thunder
#

let's say I want a learning hint to appear only once when player interact with a thing

#

making a bool check is easy but is there anything smarter than that?

#

I thought of making a delegate and assigning it depending on if bool is true or false on a Awake

#

so you don't waste performance for bool check

#

I mean in this context bool is either this thing have been shown or not

cosmic dagger
real thunder
#

you do a bool check each time you do the interaction tho

#

while delegate assigned once

#

anyway is there a saner solution?

cosmic dagger
sour fulcrum
#

delegate type stuff might make more sense from a code architecture point of view (maybe) but yeah not for performance

cosmic dagger
real thunder
#

I dunno how does it work under the hood

#

I am assuming if it's assigned it's called or u get an error in case it's not

#

which is not a check?

#

I actually saw a code doing a delegate thingie instead of, well, not bool but an enum check which is prolly more expensive than bool check but still

cosmic dagger
real thunder
#

why would I

#

if it's assigned once on Awake

#

and Update can't run before that

sour fulcrum
#

You would be unassigning from the delegate once the tip is shown?

#

So it’s only shown once?

real thunder
#

I d reassign it that moment yes

#

I d still save the bool about it and each game opening

#

choose a delegate with check or without check

sour fulcrum
#

no that’s psychotic

real thunder
#

laughs diabolically

#

but like seriously isn't it better

fading marten
#

I don't know what to do

swift crag
#

Calling a method is significantly more expensive than branching

#

A delegate that’s null when you don’t need to show the tip is probably equivalent

grand snow
#

something something branch prediction

ivory bobcat
cunning bramble
#

Hi guys,
Does a Website or what every exist where i can see c# or Unity related code that i need to fix because i wanna get better

fickle plume
pearl isle
#

hi guys ! I'm trying to follow a tutorial in which my sprite has to be a child of my text; unfortunatly in doing so, my text disappears (my sprite gets rendered before my text as following the hierarchy.). Unfortunately, the Canvas Renderer is useless because all I can do is click the Cull Transparent Mesh button. Is there any way to fix this issue ?

fickle plume
pearl isle
fickle plume
pearl isle
#

Oh alright, thank you ! Sorry for the bother

iron ether
#

Could anybody help me and my friends make a game

frosty hound
radiant voidBOT
# frosty hound !collab

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• ** Collaboration & Jobs**

real thunder
real thunder
stray anvil
#

👋 Hey everyone! Welcome to my channel! 🎥

I'm Vito, a 23-year-old who just started my YouTube journey in 2024, creating videos on 3D modeling with Blender! 🚀 Whether you're a beginner or an expert, there's something here for you.

Join me as I explore the world of 3D modeling, sharing tutorials, tips, and behind-the-scenes looks at my p...

▶ Play video
real thunder
#

not in default Unity for sure

tacit galleon
#

guys... is it a good idea to remake the whole nav mesh, and replace it with way point? Because of the player movement being so goddamn complex, the enemy appears to be extremely dumb, so i want them to be able to jump, wall run, wall jump, even ceilling running.

And the player movement is walking, running, jump, 2 air jumps, wall run, wall jump, while running on the wall we can go up or down, ground slam.

real thunder
#

it's "just make your own engine" category of a good idea

#

that said...

real thunder
#

huh, the guy developing a zero gravity shooter with proper AI companions and enemies
impressive

elder hearth
#

Hi! I was wondering if there's a way to make it so I don't have to set my bools back to false after an input toggles it to true?
So this is the code to read the input and set a bool to true

        void OnCrouch(InputValue value)
        {
            CrouchIsPressed = value.isPressed;
        }

and after this in the script(s) that read the bool I have to set it back to false!
So

            playerManager.CrouchIsPressed = false;
gloomy vine
#

Why I can't see the blue surface of the navmesh?
I have gizmos enabled, "show navmesh" set to true, baked the mesh

stark helm
#

How can make it so that I have a function that I can acces from any script?I dont need the function to be in a physical object tho

#

Interfaces dont seem to be it

#

so what can I use to achieve that?

elder hearth
stark helm
gloomy vine
#

well there is like 100 ways to approach this depending on your needs

#

you can create a new instance of that class in ur script for example

elder hearth
#

That is also true

gloomy vine
#

or just use static

elder hearth
#

you can also make it static

gloomy vine
#

or dependency injection

elder hearth
#

a regular C# script

gloomy vine
#

and so on

stark helm
#

I will try those now

elder hearth
#

I'd recommend searching it up, these are some basic OOP principles

#

Especially in C#

gloomy vine
#

exactly

elder hearth
#

Honestly I can't beleive there are non OOP langs, it would be absolute HELL for me

#

I love my OOP langs

stark helm
#

@elder hearth Would this cause lag?

elder hearth
stark helm
#

If I have 100 of those it would be laggy?

gloomy vine
#

it creates a new instance of a class

#

and no, this wont be laggy

#

u can spawn million of these

#

and it wont be laggy

elder hearth
#

Exactly

stark helm
#

how do I reference a GameObject in the Hitbox_Module? Grabbing and dragging won't work, do I use scriptable object?

queen vale
#

transform.Parent, GetComponent, etc.

stark helm
#

its just there

elder hearth
stark helm
#

so I use scriptable object no?

elder hearth
#

No

stark helm
elder hearth
#

It calls a reference of it

stark helm
#

That is all guys

#

thanks

elder hearth
#

No problem!

thick garnet
#

Does anyone know a platform for laypeople who want to learn coding to make games for beginners?

night raptor
thick garnet
night raptor
rough granite
thick garnet
hardy pewter
#

Lol started with kaplay joined unity now I'm traumatized guys who understands properties 🥀

naive pawn
#

if so,

#

!ask

radiant voidBOT
# naive pawn !ask

:thinking: Asking Questions

:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.

-# For more posting guidelines, go to #🌱┃start-here

hardy pewter
sage mirage
#

Greetings game developers 👋

So, I came up here with a problem in my shoulders/back. So, the problem is that I am trying to randomly choose 1 of 2 tags I have for 2 power ups and I want to store this random value on a variable.

#

There aren't string parameters for Random.Range() and I really would like to have some help 🙂

#

So, the problem is that I want to actually spawn a random power up at specific spawn points but I have to choose between those 2 power ups randomly

#

and now I am thinking how to make it work XD

night raptor
#

Generate a random number and compare

sage mirage
#
{
    int rand = Random.Range(0, 6);
    GameObject powerUp = ObjectPoolManager.Instance.GetObject(LIVE_TAG);
    powerUp.transform.position = spawnPowerUpPoints[rand].transform.position;
    return powerUp;
}```
#

This method was working when I had only 1 power up

#

now I have to do the above

night raptor
#

If you want equal chance, get a random int between 0 and 1 lets say and make 0 yield the first power up and 1 the second

naive pawn
#

a bit more complex if you want weights, but it's the same general idea - have a mapping between things you can randomize (numbers, discrete or continuous) and the outputs you want (arbitrary discrete values)

sage mirage
#

wait key value pair maybe?

#

HashMap

#

yes

naive pawn
#

no

night raptor
#

I wouldn’t do that. Array is already index to item mapping

sage mirage
#

oh shit I got confused with this a bit let me brainstorm a bit

naive pawn
#

mapping does not mean a Map structure

#

a mapping is just an onto function

#

i love how we give direct answers and then you extrapolate to make it both more confusing and complex

night raptor
#

I mean it would work but is just not required nor is it as efficient

naive pawn
#

would be more fragile and more work to add/remove elements

cosmic quail
#

!collab 👇

radiant voidBOT
# cosmic quail !collab 👇

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• ** Collaboration & Jobs**

sage mirage
# naive pawn a bit more complex if you want weights, but it's the same general idea - have a ...

By the way, I did it like this too simple no hash maps or anything just an array.
```public GameObject SpawnPowerUpAtRandomPoints()
{
int randPoint = Random.Range(0, 6);
int randTag = Random.Range(0, powerUpTags.Length);

    powerUpTag = ChooseRandomPowerUps(randTag);

    GameObject powerUp = ObjectPoolManager.Instance.GetObject(powerUpTag);
    powerUp.transform.position = spawnPowerUpPoints[randPoint].transform.position;
    return powerUp;
}

public string ChooseRandomPowerUps(int randTag)
{
    string powerUpTag;

    if (powerUpTags[0] == powerUpTags[randTag])
    {
        powerUpTag = powerUpTags[0];
        Debug.Log("Power up is: " + powerUpTag);
    }
    else
    {
        powerUpTag = powerUpTags[1];
        Debug.Log("Power up is: " + powerUpTag);
    }
    return powerUpTag;
}```
#

and if I have more powers ups I wont make if else if all the time, probably I will have check each element in the array and compare it with the rand tag

#

using a for loop lets say

broken nest
#

kinda noob question but how do I rotate an UI element?

#

Through code obviously

sage mirage
broken nest
#

connexionImages[i].GetComponent<RectTransform>().Rotate(new Vector3(45f * connexionList[i].connexionDirection, 0,0)); Like that?

#

I want to apply an angle according to an int

#

around the z axis cos i'm in 2D obviously

sage mirage
#

I am not 100% sure but if you want Angles you have use Quaternions

#

Not a vector

broken nest
#

The Rotate function uses a 3 axes of rotation system called euler angles

sage mirage
#

yes it is quaternion.Euler

#

or euler angles specifically

broken nest
#

I'm not too familiar with how it works but yeah it takes a Vector3

#

Never used RectTransform.Rotate() we'll see if it works

sage mirage
#

I am not really familiar as well to tell you I am practicing a lot and Game Math is hard concept

sharp bloom
#

Isn't "game math" mostly just linear algebra?

#

I'm not the best at it but it's kind of fun when you start to "get" it

sage mirage
#

statistics and probability are everywhere in AI like steering behaviours and more advanced systems I think

woeful scroll
#

hello can i send a vid to ask about some stuff and wanting some advices??

sage mirage
#

not here

#

if its unity specific yes

muted sand
#

Mainly

woeful scroll
#

it is unity 2d but like ability system

sage mirage
#

what is it

woeful scroll
# sage mirage what is it

it is more like a show case but anyway. i have made this can anyone give any advice(except the asset, currently i have none, players are using lpc), and about the vid quality, had to compress it for <10mb limit.

sharp bloom
muted sand
sharp bloom
#

Yeah the answer I got was pretty much "Unity is not meant for perfectly real-world physics simulation"

elder hearth
#

Hi! So I have this if statement

  if (grabbed == true)
  {

      this.gameObject.transform.parent = grabber;
      this.gameObject.transform.position = grabber.position;
  }
``` and the line 
  this.gameObject.transform.position = grabber.position;
solar hill
#

how are you verifying that "grabber" isnt null, what even is grabber in this context?

polar acorn
solar hill
#

is it declared as a gameobject?

elder hearth
elder hearth
solar hill
#

can you answer all the questions, how is grabber declared?

#

is it "public GameObject grabber;"

elder hearth
#

its is Transform grabber;

solar hill
#

how did you assign the reference?

#

through the inspector or through code?

polar acorn
elder hearth
polar acorn
elder hearth
polar acorn
#

You can assign a parent to null, that's how you unassign a parent

elder hearth
#

exact *

polar acorn
#

Grabber is null

elder hearth
#

Oh

#

i did not know that tbf

verbal dome
verbal dome
#

Not sure if the other physics backends are better at that

#

But maybe

sharp bloom
#
async void SomeMethod()
{
  await SomeRecursiveMethod();
  print("recursive function is finished!");
}

async Awaitable SomeRecursiveMethod()
{
  if (some condition) { 
    await Awaitable.WaitForSeconds(1)
    "(do something...)"
    await SomeRecursiveMethod()
  }
  else ( "(somehow mark function as complete?)" )
}

Is it possible to achieve this type of behavior with async/await? (Calling a recursive function and somehow waiting till its done recursing?)

#

Or is this a bad idea?

#

Because I'm pretty sure the print would happen immediately after the first "WaitForSeconds"

verbal dome
#

Mark function as complete, wouldnt that just mean returning?

#

await makes it wait for the method to finish until continuing to the next line

#

So you'd see the print only after everything in the recursive method finishes

sharp bloom
#

So it does work like I thought huh

#

I was afraid that this line would immediately make the function count as "complete"

verbal dome
#

Nope, it just pauses for that duration

sharp bloom
#

I see

turbid jolt
#

hello idk if this is the right channel but i am stuck for my assisgnment im supposd to make a tank game, im following this tutorial to make my tank shoot: https://www.youtube.com/watch?v=1rohOpl9Tq4 , it pops up with this error no matter what i do wether i have the bulletspawn and bullet attached to the tank turret or not, one difference i noticed between mine and the video is:

In this tutorial, you'll learn step-by-step how to create a controllable tank game in Unity. From setting up the tank model to implementing smooth controls using input handling, we'll cover all the necessary components to make your tank move and respond to player input.
VS Code Download: https://code.visualstudio.com/download
Asset Download: htt...

▶ Play video
#

mine does not have this

#

i cant connect the bullet spawn to the bullet

grand snow
#

See how it even told you its on line 21?

turbid jolt
#

ah i completely missed that ty

#

let me retry

grand snow
broken nest
#

I have this old piece of code and I can't remember how it works,

[System.Serializable]
public class UnityCustomEventIntBool : UnityEvent<int, bool> { }

public UnityCustomEvent customEventIntBool;
customEventIntBool.Invoke()

Will it call the method I put in editor with a bool and an int as parameter?

turbid jolt
#

i tried to change it from the rb thing i had before (as it said that was an issue) but now it pops up with this which idrk what it means 😭

swift crag
#

You had to create a class that derives from the generic type, then serialize that class

#

Invoke is going to want two arguments (the int and bool values to pass to whoever has subscribed to the event)

#

so you'd do something like customEventIntBool.Invoke(100, true);

grand snow
#

You are trying to use the type name

broken nest
swift crag
#

your example shows you invoking the event via a script

turbid jolt
minor pawn
grand snow
swift crag
#

Rigidbody is the concept of a physics object; rb is a variable containing a specific physics object

turbid jolt
broken nest
#

Bruh I've been coding for 3 days without touching editor and somehow the editor had warnings pop up at least 5 times what is wrong

minor pawn
broken nest
#

I mean I'm coding on visual studio and Unity has bugs when i don't touch it

#

I have the recommended version is there that much bug? My project is almost empty

swift crag
#

what are these warnings?

turbid jolt
#

me again, after the scripts and stuff added although works wonderfully you can see the 1st bullet is kind of stuck in place, if i dont move the tank at the beginning and shoot it, it goes at a very high angle, but if i move it then it bugs like in this video and stays still, however the clone bullets that come afterwards when i press space shoot exactly how i wanted them to so idk why the first one is like that basically compared

twin pivot
devout otter
smoky breach
#

How can i make an attribute sum 1 each time a condition its true? currently it just keeps adding 1 to the total per frame the button is pressed

wintry quarry
#

instead, do it whenever you actually want to be adding 1

#

"each time a condition its true" is really vague

smoky breach
#

example i have
if (isAttacking){combo +=1;}

wintry quarry
#

how often do you actually want that to happen?

#

You need to provide more context here

#

Maybe show your code

smoky breach
#

its in a function i call inside update, its a combo counter, so each time you press the button it adds one and then reset after a time

wintry quarry
#

When you press the button?

#

There still isn't enough information here for me to give you practical advice

minor pawn
smoky breach
#

I had to change the combo count to just be equal instead of adding, but i realized i'm going to need to add to it instead of just hard coding the value for future use

grand snow
#

that single line if is a crime

#

auto format that shit

wintry quarry
#

and yeah the least of it is the formatting

#

is this code run unconditionally in Update? It's not clear what's going on here, and I think parts of this need to be separated out.

  • Some of it should only be running when you press the button
  • Some of it should be running in Update
placid solstice
#

hey guys

#

where can i begin in Unity?

#

i find a tutorial, dont worry

wintry quarry
radiant voidBOT
placid solstice
fading marten
#

Hey guys, do you know why I can't drag and drop mp3 files into Unity?

wintry quarry
fading marten
wintry quarry
naive pawn
#

does it happen with other files?

fading marten
wintry quarry
#

Are you dragging into the Project window, or elsewhere?

fading marten
#

I'm trying to put it into a folder

wintry quarry
#

Not in Packages?

fading marten
fading marten
naive pawn
#

well people have gotten that before but i don't remember what it was or how to fix it

wintry quarry
# fading marten yes

What happens if you just move the file from windows explorer? Like instead of dragging it inside the unity window, just manually move it into the folder you want from windows file explorer

broken nest
#

Why does this monPark[monParkIndex].monsterName = ""; Doesn't work?

{
    public string monsterName;
    public string[] currentSpells;
    public int naturalHealth;
    public int naturalStrength;
    public int naturalMagic;
    public int naturalArmor;
    public int naturalResilience;
    public int naturalSpeed;
    public int currentStrength;
    public int currentMagic;
    public int currentArmor;
    public int currentResilience;
    public int currentSpeed;
}```
public List<MonStats> monPark = new List<MonStats>();```
wintry quarry
naive pawn
#

can you be more specific about how it doesn't work

broken nest
#

It says that the return value of List<MonStats>.this[int] because it's isn't a variable

#

I have no problem doing it when it's not in a list or array

wintry quarry
#

You can only use this syntax for structs with arrays

#

You need this:

MonStats stats = monPark[monParkIndex];
stats.monsterName = "";
monPark[monParkIndex] = stats;```
naive pawn
wintry quarry
#

It would also work with your current syntax if MonStats was a class instead of a struct

wintry quarry
#

But the problem with trying to do this with a List is that the indexer returns a copy of the struct

naive pawn
wintry quarry
#

so modifying that copy would not do anything - and the compiler gives you an error instead of letting you footgun yourself.

broken nest
#

okok ty

#

ty

broken nest
wintry quarry
#

As for the question of class vs struct - I don't know enough context about your code this to answer that really

broken nest
lyric pebble
#

How should I start to learn c#

wintry quarry
#

Then move onto the Unity learn stuff

lyric pebble
#

Thank you so much😭😭😭😭

timber tide
#

https://www.w3schools.com/cs/index.php
w3schools has a very simplified introduction of concepts

placid solstice
#

hello im trying use the key pressing system and this error appears

#

"if (Input.GetKeyDown(KeyCode.Space))" this is the problem line i guess

#

how can i fix it

fair cedar
#

i think you are doing it like the old input manager

#

i just swapped to the old input manager

#

idk if that is good but it was mostly for following tutorials

placid solstice
#

i change it in Player Settings

#

but, how is the new input manager?

#

like, the code

fair cedar
#

you could use both

fair cedar
#

but i am still trying to learn so i am sticking to the old one for now

#

I am trying to make a smash attack for my game, and the way it works is = press key > jump > land and push nearby enemies away. First it kinda worked only, but the smash attack was doing when i was jumping up not when i was landing, but now when i use grounded bool, it still does the attack when jumping, because I guess the force hasnt really moved my player enough up to not be grounded anymore??? is there a way to delay something by one frame ? ```
if (Input.GetKeyDown(KeyCode.Space))
{
if (canSmash)
{
playerRb.AddForce(Vector3.up * jumpStrength, ForceMode.Impulse);
canSmash = false;
smashing = true;
}
if (smashing && grounded)
{
smashAttack();
smashing = false;
}
void smashAttack()
{

    for (int i=0; i < spawnManagerScript.enemies.Count; i++)
    {
        GameObject enemy = spawnManagerScript.enemies[i];
        Rigidbody enemyRb = enemy.GetComponent<Rigidbody>();
        Vector3 awayFromPlayer = (enemy.transform.position - transform.position);
        enemyRb.AddForce(awayFromPlayer * smashStrength, ForceMode.Impulse);
    }
}
#

the code is probably bad so any advice would be great

#

how do i make it so that the smash attack wont do when it has not jumped yet, but when it landed from it?

next yarrow
next yarrow
#

you should keep track of "did the player jump already?"
If they did, only then, when grounded becomes true again, you smashAttack()

fresh wadi
#

hey guys im really stuck on this issue im trying to make it so when the mouse is over a certain object it moves towards one side like left to right i know trasform position exists its more that getting the mouse over a game object or ui element to updates its position

next yarrow
fresh wadi
#

i found a solution but it only worked for text which is a ui element

next yarrow
#

you're asking how to know if the mouse is hovering a gameObject?

fresh wadi
#

yes

next yarrow
#

IPointerEnterHandler should be your answer then

fresh wadi
#

ive entered the code that unity has provided documentation for IPointerEnterHandler and attached to a simple 2d square nothing is happening

#

all i want it to do is when i hover over the mouse over a certain game object it change a variable to 1

rich adder
#

otherwise you can just use a regular 2D overlap point

fresh wadi
#

or is it a spefic component

rich adder
keen bridge
#

hello,

I have currently making a unit movement script and I need to link a layer to the script, I have made a "layerMask" variable, but the "ground" variable is not appearing in the script. Would anybody be able to point out why this is?

north kiln
#

!ide

radiant voidBOT
north kiln
#

Because you have an error in your code and you can't even see it

keen bridge
#

okay thank you, will take a look 🙂

north kiln
#

Also when posting code it's best to link to it, because then it can be copied to help, and it'll always include line numbers (which you have cropped off)

radiant voidBOT
keen bridge
grand badger
keen bridge
#

also,

I am following a guide on youtube, he is on an older version of unity by the looks of it, my animation screen looks nothing like what he has. Am I on the wrong tab, or has it just been overhalled alot?

slender nymph
#

the left is the animator window, while the right is the animation window. two completely different windows

keen bridge
#

oh i see, how do i open the animator window? i do not see that in the dropdown

slender nymph
#

use the Window menu at the top rather than that context menu

broken nest
#

I have this script database where I store all my scriptable objects. Can I change them at runtime? like sprites and all?

keen bridge
#

thanks, got it 🙂

slender nymph
broken nest
# slender nymph this is really not enough info to go off of. but if you are referring to modifyi...

What do you mean by that? I have this script public class DataBase : MonoBehaviour { public static DataBase instance; public void Awake() { if(instance == null) { instance = this; } else { Debug.LogError("more than 1 DataBase"); } } public List<ScriptableObjectMonster> scriptableMonsterList = new List<ScriptableObjectMonster>(); public List<ScriptableObjectSpell> scriptableSpellList = new List<ScriptableObjectSpell>(); public List<ScriptableObjectLevel> scriptableLevelList = new List<ScriptableObjectLevel>(); public Sprite backgroundForest; public Sprite backgroundSavana; public Sprite backgroundIce; public Sprite backgroundTropical; public Sprite grassForest; public Sprite grassSavana; public Sprite grassIce; public Sprite grassTropical; }

slender nymph
#

which part of what i said are you not understanding?

broken nest
#

Can I modify the scriptableObject at runtime

#

Ah ok

slender nymph
#

if you are referring to modifying the properties of a ScriptableObject at runtime, you should ideally avoid doing so because it behaves differently in the editor than it would in a build

broken nest
#

Then Idk I'll figure something out then

cosmic dagger
#

If you want to mutate or change the data, it's better to use a runtime class and copy the SO data to it, then you would use that—class—instead . . .

lean sandal
#

Hey Im looking for some good beginner courses to learn C# with unity for game design and development, and something that I can use to build some basic games and learn to add some new things to it? Can anyone recommend something please? Thank you so much.

teal viper
#

!learn

radiant voidBOT
teal viper
#

Also, literally, top 10 results in Google.

lean sandal
#

Thank you I will go do some more of those courses I have done alot of them before and they seemed outdated

#

they also didnt seem to go very far beyond certain things, or were very scattered idk

teal viper
#

Most of it still applies with minor changes. Mostly api renames or method signature changes.

teal viper
lean sandal
#

I want to learn all the basics right now of code, then just make some small games to practice, like 2d flappy bird etc

#

which Ive done those before already I just need something that goes a few steps further

bold root
#

Hi ive spent around 4 hours now in unity (so an extreme beginner) and I dont understand why the game view isnt scaling properly from the scene view. Any insight onto where the problem comes from?

gusty anvil
naive pawn
#

is your camera set up correctly?

bold root
bold root
sour fulcrum
#

theres a camera component on an object in your scene

#

that controls what your game view is like

#

the scene view is just for your ability to edit stuff

naive pawn
bold root
#

so where do I go to fix it

naive pawn
bold root
#

theres this part saying main camera

naive pawn
#

that's an object and it has the Camera component

bold root
#

but i dont know what im supposed to tweak to change the view

naive pawn
#

if you select that object you can see a preview of what the camera is looking at

#

change the size of the camera

bold root
#

so theres no auto scale to the objects ive already set up?

naive pawn
bold root
#

i didnt get anything from anywhere

naive pawn
#

auto scale isn't a thing

sour fulcrum
#

you could do that with code but

#

for this you probably just wanna adjust the position of the gameobject that has your camera component

#

and maybe the size and/or field of view on the camera component

naive pawn
#

(would not be fov)

bold root
bold root
naive pawn
bold root
#

yes

#

I made the same change out of play mode and got different results

naive pawn
#

as in the size changes again when you enter playmode?

bold root
#

start with size 5 then change to 10 in play mode

naive pawn
#

not sure what you mean by that

bold root
#

start with size 10

naive pawn
#

ah

#

check the inspector, see if it's changed back to 5

bold root
#

it shows 10

bold root
#

when I start with size 10

naive pawn
bold root
#

this is what im changing on the camera is there another section im supposed to change

naive pawn
#

this should be it

naive pawn
#

as in, the camera frame encompasses the entire board?

bold root
#

yes

#

actually it zooms in to the perfect spot on scene view with camera size 10, was a little small on 5

naive pawn
#

make sure you only have 1 camera in the scene, i guess?

bold root
#

but game view doesnt change based on the camera size setting

#

but when i change the size inside playmode it fixes the problem

bold root
naive pawn
#

so make sure those other objects don't have Camera components

bold root
#

which means?

onyx ridge
naive pawn
#

have you gone through unity essentials on unity learn

bold root
naive pawn
#

do you know what a component is

bold root
#

This is all thats there

#

the only thing i added was the chess board object with a script to make the board and add the pieces

#

no camera

naive pawn
#

so do you know what a component is

bold root
#

the parts on the right?

naive pawn
#

sure, i guess

#

try searching for t:Camera in the hierarchy, to confirm there's only one camera

onyx ridge
#

Hiearachy, inspector, components, prefabs, instances, project window, scene view, game view, gizmos etc

naive pawn
#

make sure the scene is saved i guess

bold root
#

Is there a way to resize the camera with sliders instead of just the size? the shape is all off

#

If i hover the main camera i can see what its looking at on the scene thats why its messed up, I suppose I could try to make all the objects smaller but id rather just make the camera fit it if possible

bold root
keen dew
#

The shape is the shape of the game window or the player's monitor when played in fullscreen. You can't physically change the monitor size

bold root
#

ok so somehow when I change the camera size its changing the scale that my objects render. I will need to look into that

#

found it, thanks team

onyx ridge
bold root
#

kind of makes it seem impossible to develop for different screen sizes if theres no auto scaling mechanic

sour fulcrum
#

there is but it gets a bit complicated 😅

ionic zealot
#

https://codeshare.io/5Dw7EW Hi yall, I know mixing ui positions and world positions isnt ideal, but i really like how it is right now, though I dont know why it always puts out a 200~ instead of actually varying output, please help

bold root
onyx ridge
tender mirage
#

Curious, is there a way to call a function parameter with multiple lines?

//Add keywords
keywords.Add(){ 

    new keyword(new string[] { "armored" }, "Armored", "<sprite name=\"Armored\">", true);

}
;
stoic mural
stoic mural
stoic mural
naive pawn
#

you can just put a newline after (

#

eg

keywords.Add(
  new Keyword(...),
  new Keyword(...)
  // etc
);
```if the function allows that
if `keywords` is a List or something like that doesn't allow that, you can just add them in separate function calls
#

there is also collection initialization syntax, though i don't remember if unity's version of c# allows it

tender mirage
#

Thanks for the help.

naive pawn
tender mirage
# naive pawn also just btw, types should be in PascalCase, so `keyword` there should be `Keyw...

that was just a little typo, no worries there.

else it looked like this before

//Add keywords
keywords.Add(new keyword(new string[] { "amphibious" }, "Amphibious", "", false));
keywords.Add(new keyword(new string[] { "antihero", "anti hero", "Anti Hero", "Antihero", "AntiHero", "anti-hero", "Anti-hero", "anti-Hero" }, "Anti-Hero", "", true));
keywords.Add(new keyword(new string[] { "armored" }, "Armored", "<sprite name=\"Armored\">", true));
keywords.Add(new keyword(new string[] { "bullseye" }, "Bullseye", "", false));
keywords.Add(new keyword(new string[] { "deadly" }, "Deadly", "", false));
keywords.Add(new keyword(new string[] { "Doublestrike", "doublestrike", "doubleStrike", "double strike", "double Strike", "Double strike" }, "Double Strike", "", false));
keywords.Add(new keyword(new string[] { "frenzy" }, "Frenzy", "", false));
keywords.Add()
naive pawn
#

that seems normal

#

that was just a little typo, no worries there.
you still have keyword in this newer snippet

tender mirage
#

honestly i didn't even catch the lower case k. i was wondering why it was throwing an error

sour fulcrum
#

your not meant to, your IDE is

#

!ide

radiant voidBOT
tender mirage
#

yeah visual studio like 50% of the time isn't throwing errors actively for some reason

#

ever since i started using the 2026 build

sour fulcrum
#

Also just a random observation take it or leave it but you could potentially automate those long lists of strings

naive pawn
#

regex time wooooo

tender mirage
sour fulcrum
naive pawn
#

could just be like /anti[- ]?hero/i

bold root
sour fulcrum
#

im not regex pilled but if you force lowercase whatever the input is there's only 3 variants right?

  1. no space, no hyphen (antihero)
  2. space, no hyphen (anti hero)
    3 hyphen (anti-hero)
bold root
sour fulcrum
#

it would be heavily intertwined with lichess's code and also it's not made in c#

naive pawn
#

well, it is open source

tender mirage
bold root
tender mirage
#

It's hard to briefly explain but it's already abit messy

sour fulcrum
naive pawn
#

the chess logic appears to be in its own repo in ts, which is close to c#

#

fwiw i'd still recommend making it yourself though, especially if you don't have much experience

#

it's pretty easy to get lost in a pre-existing codebase

sour fulcrum
#

if you don't have much experience making chess sounds like a nightmare

naive pawn
bold root
naive pawn
#

just so you know what's going on as a whole

sour fulcrum
#

Sebastian Lague has two videos on his adventure making chess in unity, you probably can't use it as a tutorial but he does provide source afaik
https://youtu.be/U4ogK0MIzqk?si=gKrEy24O6F38DMX0

My attempt at creating a little chess playing program!
Think you can beat it? Give it a go over here: https://sebastian.itch.io/chess-ai

Support my work (and get early access to new videos and source code) on Patreon or Nebula

Source Code:

  • GitHub:...
▶ Play video
naive pawn
#

as a beginner, understanding a whole foreign codebase to a degree you can integrate it with your own systems would probably be harder

tender mirage
bold root
sour fulcrum
#

that is still like

#

chess code is really complicated

#

because of the ai stuff

bold root
#

What ai stuff

#

I don’t need an engine to analyze games, but that’s not that hard anyways

naive pawn
#

a chess bot

tender mirage
#

Maybe some chess bots have parameters built into them for you to modify.

bold root
#

All you need is the fen for a given position

#

Which is easy to extract

#

Then plug the fen into the engine and it tells you the analysis

#

But I don’t really need that for my use case anyways

#

I just need a playable game board and to implement all the things you’re not allowed to do

#

Currently I can move any piece anywhere at any time notlikethis

naive pawn
#

chatgpt chess

boreal sonnet
#

i give the camera the position of player to follow but it shows the background too how can i fix it?

#

can anyone tell me?

naive pawn
#

what do you mean by "it shows the background"

#

that's what a background is...?

#

or do you mean the background of the scene or something

fair cedar
boreal sonnet
#

see the border ... it show beyond the border and with ui also show outside the border

#

in scene the camera should only show the inside of the border but the outside of border is also shown

fair cedar
ionic zealot
naive pawn
#

anyways which line/method has the issue?

ionic zealot
#

Ohh, okay, Ill change that, ty

#

void ResolveShot(bool won) Distranced always calculates to about 200~

boreal sonnet
#

can anyone tell what is the issue?

ionic zealot
#

It used to work, but i changed the camera angle a bit and now it kinda all just goes to that

naive pawn
#

(also shouldn't this practically be in world units)

ionic zealot
#

What do you mean? Cause i aint sure how to really convert it, but i know checking 2 numbers being within a certain range shouldve worked preety well

naive pawn
#

screen units are in pixels, the same physical distance could have different screenspace distances for monitors of different resolutions

ionic zealot
naive pawn
#

so are those the values you expect?

ionic zealot
ionic zealot
naive pawn
#

convert the reticle to worldspace and get the worldspace distance

naive pawn
#

also shouldn't you be using anchoredPosition for RectTransforms, rather than position

ionic zealot
#

No, just the difference

naive pawn
#

and do they match what the logs say they are

ionic zealot
naive pawn
#

are you moving the position or the anchoredPosition?

#

(when you tried anchoredPosition)

ionic zealot
naive pawn
#

try using anchoredPosition i guess

#

and make sure you're also using anchoredPosition when moving it

ionic zealot
real thunder
#

I was doing something like that successfully

#

no idea what is the best way

ionic zealot
#

I see

#

I dont really even need the best way, Im doing this for school and it's not really expected, I just rlly wanna make it nice cause it fun to work on

boreal sonnet
naive pawn
#

the game view seems to be aligning with the camera edges just fine?

#

the scene view should not be affected by the camera setup

boreal sonnet
#

i know i even tried cinemachine camera & cinemachine brain but after the game view disappears

naive pawn
#

the scene view is the stuff in the scene, the stuff that exists in the game world
the game view is what a player would see, as rendered from the cameras in the scene
you're free to move around in the scene view, it's unrelated from the cameras that exist in the scene

boreal sonnet
#

i know but the camera position is what is important i change it different aspect ratios . it only show the middle scene?

naive pawn
#

what middle scene

real thunder
# ionic zealot I dont really even need the best way, Im doing this for school and it's not real...
float half_marker_x = main_rect.localScale.x * main_rect.sizeDelta.x / 2;
float offset_x = offset_sides;
float bulk_offset_x = half_marker_x + offset_x;
void case_right_side()
      {
        float enclosed_y = (Screen.width / 2 - bulk_offset_x) * tan;
        if (screen_location_from_center.y <= 0) enclosed_y = -enclosed_y;
        marker_position = new Vector3(Screen.width / 2 - bulk_offset_x, enclosed_y, 0);
      }

this is a piece of code I use to clamp UI element to the sides of the screen and I absolutely hate it and don't remember how it works

boreal sonnet
#

this ?

naive pawn
#

the middle of the scene?

boreal sonnet
#

when ratio is change .you see it in photo

naive pawn
#

what's the issue though

boreal sonnet
#

the camera range

naive pawn
#

this is how it's supposed to work

boreal sonnet
#

i know ..listen when i play the game the camera shows the outside part of the border and that's not how its suppose to work right?

naive pawn
#

the scene or the game view?

#

the scene has a separate "scene camera", it's not using the one that's in the scene

#

the one that's in the scene renders to the game view

boreal sonnet
#

the game view is the issue

#

wait

naive pawn
#

where's the issue

boreal sonnet
#

thats the issue the position of the camera is concern as it also show it in different ratio

naive pawn
#

the position of the camera isn't changing when you change the ratio

#

just circle the part you're saying is an issue or something

#

are you referring to the letterboxing of the game view?

boreal sonnet
#

ok you player 2d game the camera only show the player and border behind it right ?

#

that i wish to do

naive pawn
#

i have no idea what you're saying

#

borders typically aren't behind the player

#

if english isn't your first language, feel free to use machine translations

#

which border are you referring to

#

draw a circle around it or something

boreal sonnet
#

the border on playes's left side

naive pawn
#

the level border?

#

dude you gotta get better at communication

sour fulcrum
#

sorry to interject; i'm being a bit of a dingus tonight and can't figure out what i'm missing here in order to correctly get my voxel positions to be correctly in the bounds like it does when its set to 2

    private void MakeVoxels(Vector3 voxelCount, Vector3 voxelSize)
    {
        int count = 0;
        for (int y = 0; y < voxelCount.y; y++)
        {
            for (int x = 0; x < voxelCount.x; x++)
            {
                for (int z = 0; z < voxelCount.z; z++)
                {
                    Vector3 pos = new Vector3(x * voxelSize.x, y * voxelSize.y, z * voxelSize.z);
                    pos -= new Vector3(voxelSize.x / 2, voxelSize.y / 2, voxelSize.z / 2);
  
                    Gizmos.DrawWireCube(pos, voxelSize);
                    Handles.Label(pos, count.ToString());
                    count++;
                }
            }
        }
    }
#

if anyone can spot what im goofing on it would be kindly appreciated

naive pawn
naive pawn
sour fulcrum
#

trueee ty

naive pawn
#

also fwiw mp4s would be better than gifs

#

i can't pause this

sour fulcrum
#

that is very fair, i gotta set that up

naive pawn
sour fulcrum
#

correct, sorry for not sending that

naive pawn
#

where's the origin, relative to that big cube?

#

ah wait i think i see the issue

sour fulcrum
#

all of this is vector3.zero with no rotation or scale

naive pawn
#

hm wait no i'm not sure it's the cause here, but it could be contributing

#

you're starting at 0, and you're shifting the pos to account for the center by subtracting, so you'd get some negative results

either start at 1 (and use <=), or do pos += to shift the center instead

sour fulcrum
#

ohhh hmm improvement ok

#

gimmie a sec

naive pawn
#

so i think what i described would make the position consistent, right?

#

but it'd be offset by half the big cube's size?

#

since what i described basically assumes it starts at the origin

sour fulcrum
#

on the money yeah

#

we have consistently offset now

naive pawn
#

yeah you'd shift everything by -bigCube/2 or -count*size/2to get it to be around the origin

sour fulcrum
#

🙏 bless you

keen bridge
#

how should one be commiting changes to github? is there some ui in unity to make commits, push and make branches etc?

#

or should i be opening a terminal in the projects root and using git cli?

wintry quarry
#

I personally use the CLI, or these days claude code.

#

a lot of people use plugins for their IDE (e.g. Visual Studio)

#

There's probably a Unity plugin somewhere that adds stuff to the editor, but I think a dedicated git client is usually best.

swift crag
#

i just use the CLI directly

zenith cypress
#

Fork is great (app)

real thunder
#

How would I rotate a transform into a random consistent direction indefinitely?

frosty hound
real thunder
#

It want Euelers

#

oh wait I can just

#

yeah get random V3

#

why on unit sphere exactly
that will make rotation "even" along axises I guess?
if so, cool

frosty hound
#

Because it will give you normalized (length of 1) vector, which means you can multiply it by a speed value and it will be scaled corectly.

real thunder
#

won't I get valid consistent rotation if it was a non normalized vector anyway

polar acorn
#

You're gonna need to define what you mean by consistent

#

Consistent speed? Consistent direction? Consistent acceleration?

real thunder
#

won't it fit all those 3?

frosty hound
#

It would be consistent yes, as in, it won't change speed.

#

But the speed of the rotation is determine by the length of the vector. So if you want to have any kind of control over that, that's why you normalize and multiply it by a speed value.

real thunder
#

oh, that makes sense

#

I understand now, thanks

open crater
#

Guys I have a gameobject called "falling parts" and in this, i have 8 other gameobjects, everyone called platform. Lets suppose they have a rigidbody but they doesnt fall. When i press a button, they will return to the starter position, and for this reason i have to save their starter position. Can i save the gameobject position that has every object (In this case "falling parts") and set its position to the starter one by doing position = starterPosition? Or i have to use array to get every position of the gameobjects?

naive pawn
#

you don't have to use an array, there's several ways to store multiple values

open crater
#

How

naive pawn
#

if they have rbs you should use rb.position/rotation though, not transform.position/rotation

open crater
#

But can i save the starter global gameobject position in start() and then reuse it later for the respawn or i have to do it for every single item?

naive pawn
# open crater How

you could have each object have its own field, you could have an array, you could have a list, etc

naive pawn
sour fulcrum
#

are stackoverflow errors always accurate? trying to do some flood filling type shit and i can't tell if im doing it poorly or wrong

night raptor
sour fulcrum
#

that probably answers my question yeah, i'd show code but like i haven't even tried to make it good lol

#

if it can fail because its filling up too much space and gives up then its probably that

#

i don't think ? i have like a outright recursion rn

night raptor
#

So the code would be the first culprit I would look for. One common pitfall in flood filling is that you must keep track of the cells you have already visited (or some other solution to avoid duplicates). If you just blindly always explore in all directions, you will end up in an infinite recursive loop. A cell would explore the one to the right and the one to the right would explore the cell to the left and the cycle would continue until you have enough calls to fill the whole stack

sour fulcrum
#

heard chef ty

#

i think it wasn't infinite but its very unoptimised and like 216k voxels so

#

ill do some very basic optimisation and report back 😅

night raptor
#

If performance is the concern, I would recommend considering iterative solutions instead. Everything that can be done recursively can be done iteratively as well. Iterative solutions are many times if not always faster than recursion in C# like langauges. At the same time you get rid of possible stack overflows and makes it easier to debug the infinite loop issues

verbal dome
#

Use a stack or queue instead of recursion

woven scaffold
#

quick question, is there a known way to check if a string of text fits within a text mesh pro rect + margins?

#

a quick search doesnt show up much but maybe i justneed to look more

#

i feel like there is a built in way to check some variables but i cant remember what it is

verbal dome
#

Fwiw I googled

unity textmeshpro calculate text size

woven scaffold
#

does that take into account the margins as well?

verbal dome
#

No idea, tryitandsee

woven scaffold
#

welp i geuss we will see in a moment

naive pawn
sour fulcrum
#

ill have to research abit into this since i dont know how iteration based stuff could work for like 3d flood fill stuff so i might be missing out on some sauce

#

thanks for advices

night raptor
# sour fulcrum ill have to research abit into this since i dont know how iteration based stuff ...

That's exactly the reason recursion is often used, it may be easier to understand intuitively. For flood fill though it isn't particularly complicated to do iteratively. You just have to make a stack/queue where you put all the cells you would need to explore later. In a while loop you go through that stack/queue as long as there are something in there, take one cell at a time out of the stack/queue and add all the neighbours to the stack/queue to be explored by later iteration.

naive pawn
#

for depth-first stuff you need something FILO, that can be just a Stack object or the callstack - that's what the recursion achieves

night raptor
#

pseudocode:

stack = starting element
while elements in stack:
    element = get and remove from stack
    #do something with the element
    foreach neighbour of element:
        if neighbour not yet explored:
            add neighbour to stack
            mark neighbour as explored
naive pawn
#

i vaguely recall you have to check if element explored before looping?

#

gonna have to think about that for a bit

night raptor
naive pawn
#

yeah it'd reduce a lot of looping

elder hearth
#

Hi! It's me again lol, but my grab system clips objects into other GOs such as walls

    private void FixedUpdate()
    {
        if (grabbed == true)
        {
            if (this.gameObject.transform.parent != grabber.transform)
            {

                this.gameObject.transform.parent = grabber.transform;
                rb.useGravity = false;
                rb.freezeRotation = true;
                transform.localPosition = Vector3.zero;
            }
            else if ((this.gameObject.transform.localPosition).magnitude >= maxDistanceFromGrabber)
            {
                grabbed = false;
            }
        }
        else
        {
            rb.useGravity = true;
            rb.freezeRotation = false;
            this.gameObject.transform.parent = originalParent;
        }
    }
``` I have tried everything to fix it lol
sour fulcrum
#

Would it be common for not yet explored to just be some hashset that i chuck them into for comparison?

naive pawn
#

yeah

#

or a bitset, if you have sequential ids, for example

sour fulcrum
#

heard heard

#

its 1:30am so lemme finish my coffee and then i might mess with this, tyty

night raptor
verbal dome
#

(If the other option was to add them always and then continue if the element we pulled from the stack was already visited)

sour fulcrum
night raptor
sonic harbor
#

Ello im new to coding guys I dont know where to start

sour fulcrum
#

eg. i want green to flood white, so i need to explore 0 more than once because i'll miss it on the first pass

cosmic quail
naive pawn
sonic harbor
night raptor
sonic harbor
cosmic quail
#

you mean programming a trading system for your game?

#

there are probably tutorials for that on youtube

sonic harbor
polar acorn
polar acorn
sonic harbor
sonic harbor
polar acorn
verbal dome
#

New to defining things?

sonic harbor
#

wdym

polar acorn
#

This is a Unity server

#

the hell you asking about finance for

sonic harbor
verbal dome
#

Unity game engine, just to be clear

polar acorn
sonic harbor
polar acorn
#

The game engine

#

How the hell did you end up here

sonic harbor
#

got it

polar acorn
#

I guess I'm expecting way too much out of someone named "Elon"

sonic harbor
sonic harbor
sour fulcrum
sonic harbor
#

@polar acorn before i get started with coding and programming, is there any degree or qualification required or any subject req like physics,chem , maths? quantam physics?

polar acorn
sonic harbor
polar acorn
#

No, like, words

#

At least at a fifth-grade level

verbal dome
polar acorn
#

So take some time, work your way up to that, then try programming

sonic harbor
sour fulcrum
#

a different server

#

we don't do that here

elder hearth