#💻┃code-beginner
1 messages · Page 837 of 1
For some reason, raycasts have been intimidating to me so I've sort of been avoiding them
raycasts are super simple and will be a very common tool in your toolkit
All roads seem to be leading to them, so I think it's time to get over my hesitation 😅
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
processLook() is called from another manager script:
private void LateUpdate()
{
look.processLook(onFoot.Look.ReadValue<Vector2>());
}
Sorry for the code wall
hello which channel can i ask for general help in?
#💻┃unity-talk for non-programming I think
Best to use the given channels instead
oh okay, my problem is with installing unity so ill ask there.
assuming that look input is from mouse delta, don't use deltaTime for it
mouse delta is already a delta, already per frame
So I just remove both instances of DeltaTime?
yeah
you'll have to reduce the sensitivity to compensate
not sure it's the issue here, but definitely an issue
Works as expected, thanks!
Strangely the tutorial I was following used delta and it worked, but the look works for me now
Thanks again
yeah tutorials aren't always guaranteed to prescribe best practices
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
paranoid for what?
Of them eventually stealing it and making a duplicate game if it got advanced far enough
i don't think business practices are much different for any of the genAI as a service companies
they're definitely not going to do that lmao
I don't think paranoia about a specific country potentially doing something with data your providing them is suitable for this server tbh
they aren't sifting through all the input for the 0.001% that happens to be game code
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
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
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?
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
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
they aren't just republishing the code as-is
Imagine if one of your users dumped your games source code into Qwen 6 😛
machine learning training gets better when you give it more inputs and more time. the argument in that regard is that the genAI companies are effectively pirating to get more inputs/training data, and then benefitting economically from the higher-quality model
(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?
If you are implying someone is going to decompile it, i will assure that doesnt happen xd
you can't
the only 100% assurance is not publishing it to begin with
Ill be honest i really only ever hear of godot code being decompiled.
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
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
it's not 1:1, and it's made harder when there's more compilation or optimization or translation layers or obfuscation. but it's never impossible
In regards to if thats how update works, yes. In regards to help with some specific problem you might have with this, it's a little hard to get the gist of it just by reading it. you might need to do some troubleshooting (eg. some debug logging) to narrow down what's going on
also in the future post your code via
Oh so its not really decompiling its reverse engineering?
!code
📃 Large Code Blocks
Use links to services like:
https://pastes.dev/
https://paste.yunohost.org/
https://share.sidia.net/
https://paste.ofcode.org/
https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
What about it? Many of their services are on the server side.
they are very closely related concepts
note that i did not say reverse engineering
i just said reverse
Ah, thanks, I'll format better next time
Does it count as decompiling if i am analyzing the behavior of a famous game and duplicating the behavior into my game
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
(i see your question about the if's was already answered, so this is more probing into code quality)
why do you need them to be on separate frames?
no, that's reverse engineering and/or plagiarism and/or inspiration
depending on how charitable you want to be and how close you're going
having the two functions work on separate frames was just one of my attempts at fixing the flash of white. Originally it was just one frame, but I've tried a few solutions that don't seem to be working
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 )
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
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?
These patterns aren't unity specific
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
I dont think you are experienced enough then
That goes for you
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
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
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
they didn't ask
Bro even as a solo doesn't matter if you do it solo now, you will be doing it with a team in the future
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.
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.
Ok anyway my question was about DI and Service Locator Pattern
And I anwsered you how I do things, and you tried to do... I am not sure what exactly
But like the other guy said this is not Unity Specific maybe I have to ask it in programming server
What is this you mean?
I want to understand the DI and Service Locator so probably I am gonna ask and search for them
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
Currently, what I do is I have two bridge game objects like TitleSceneBridge and MainSceneBridge and I have a script for each of them a TitleSceneBridge script and MainSceneBridge script as well. So, when the player is changing a scene I am manually assigning the specific references I need on the other scene.
So I am assigning references I need at runtime
when the scene transition happens in awake if I am not wrong
Hi yall, I dont know why, but the resolveshot func doesnt seem to be getting called, please help https://codeshare.io/GkYbkw
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?
Why not just use the break statement to escape the while loop and exit properly?
oh yes
XD
And you'd want the coroutine instance, not the coroutine function (if you're really wanting to stop it)
you would use yield break to stop an IEnumerator, that's the analogue of return in this context
(but yeah you can just break the loop if it's on a loop)
oh yield break I will keep it in mind
yes, it is best to store the Coroutine in a variable, so you can use StopCoroutine(coroutineVariable) . . .
{
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?
SpawnLivesAtRandomPoints gets a new GO from the pool.
you then immediately return it
if you want to return a GO that has previously been allocated, you need to have a variable for it, and then return that
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
You should cache the spawned object before the second wait statement and despawn that object instead some other new random object
This was the problem and I figure it out
{
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 !
since you will probably be testing stuff from different scenes, I'd make a singleton where in the static getter you make a new gameobject if none already exists, and return that (or the existing one) + you can give it dontdestroyonload if it's important that whatever you need in the second scene be the same instance
if a function returns a reference type and is not idempotent, then X() is often not the same as X() 
I do use DDOL and Singletons yes
The problem is I dont want to touch right now anything because I dont want to break my code
what do you mean
and my project basically because I have chosen to create bridges and actualyl assign references I need manually
I think I don't understand what is the issue that you are trying to solve with these patterns
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
UIManager.cs
https://paste.myst.rs/bfafns6f
MainSceneBridge.cs
https://paste.myst.rs/o6wam2ui
TitleSceneBridge.cs
https://paste.myst.rs/df8h0wvt
Here
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?
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.
I want to warn you that its not a good idea to use a scriptable object for more than data storage because unity may unload and make a new instance at some point
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
{
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
Is this a reference problem or more of a rendering problem
if reference problem, understand what the sharedmaterial property is on your renderers
https://docs.unity3d.com/ScriptReference/Renderer-material.html
And read the docs on that a bit more
to be honest i couldnt tell you, im not too sure.
Are you at any point using .material on the light renderers? How did you get the reference to the ceiling light material in this script?
how i can verify the ration of white/black in a render texture?
Can you give more context? The most straightforward way is to iterate over the pixels and do the math
Are you trying to figure out how "bright" the image is?
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
what do i dod to make image 2 look like image 1
!ide
If your IDE is not autocompleting code or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
!ide
If your IDE is not autocompleting code or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
double kill
tsk, 2nd place . . .
im confused
what will you do with the result?
i try to iterate over pixel but it was by converting my rt in a texure2D and it's not optimal and very long for texting in game (that make unity crash)
on what?
i have visual studio and i alredy modified it to work with unity
you shouldn't need to convert anything to anything - you can iterate directly over the pixels in the RT.
but i don't find how
what do you mean "modified it to work with unity"
if its not working like image 1 then its not
desactive the game object if the render texture have like 70% of black
@green osprey if you did all the steps and somehow still not working, check here
https://unity.huh.how/ide-configuration/visual-studio#if-you-are-experiencing-issues
If your IDE isn't providing autocomplete suggestions or underlining errors in red, then it needs to be configured.
public static float GetWhitePercent(Texture2D texture, float threshold = 0.05f) {
Color[] pixels = texture.GetPixels();
int whiteCount = 0;
foreach (Color p in pixels) {
if (p.grayscale >= 1f - threshold)
whiteCount++;
}
return whiteCount * 100f / pixels.Length;
}
i only have this but it's for texture 2D and not for a render texture
You basically need to use https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Rendering.AsyncGPUReadback.html
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++;
}
}
});
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
Are you using version control and/or onedrive or dropbox or something
Color32 is the same as Color?
Github
similar
that was for Anacondra
I do have oneDrive
is your project inside OneDrive?
mb
yes
I made another scene today, then when I went back to the other one that one was reverted
Well first off - this is a really bad idea
Second - this sounds like you never saved your original scene OR OneDrive rewrote it from the cloud
Stop using OneDrive and switch to a proper version control system.
ok hang on, I made a demo version of the game and that one is saved
am I able to edit that demo version?
if you have the project itself and not just the game then yes
no
This is kinda like asking "if I modify this cake will that modify the recipe?"
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
You can decompile a binary but it won't be the same or guaranteed to do so
in most cases it's more trouble than it's worth
yeah you will spend more time trying to sort out the spaghetti mess it gives you than just redoing your scene.
take it as a hard lesson into using a proper version control from now on and ditch that malware called microshit onedrive
but how can it change just from going to a different scene?
if the other scene isn't saved to the filesystem, then unloading it from memory means it goes poof.
but I've closed this project hundreds of times and it hasn't gone poof
OneDrive probably overwrote it
why don't you check the history of the file in OneDrive?
Doesn't OneDrive maintain file history?
I didn't even know it was in OneDrive
it was apparently in my personal section
I don't know how to check fileHistory
Learn how to restore a previous version of a file in OneDrive using the OneDrive website.
how do you get the number of pixel at the end or how to return it in a fonction
pixelData.Length
no the variable that u created
what about it?
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
I don't see one file, I just see a bunch of files from my game
hang on, hang on
I don't see version history when I right click it
my probleme was numberOfWhitePixels beacause he was created in the lambda fonction and i can't get it but i get it now thanks
God damn it, it only says April 6th
Architecture questions
how to make cube explode into a million pieces
find a mesh fracturing asset or build it yourself
or you need to make it pre-cut yourself and have 2 versions
||Create the million pieces that fly apart from the explosion||
You can fake it also using things like VIsual Effects graph
it really depends on the usecase
what if i make a million cubes and then make a rigid body explosion
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
or put a boom texture on it and then seperate it to a million pieces
If you make a million cubes, there will be huge problems with optimization.
then connect 200 playstation 3's together
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)
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
a delegate is more expensive than a bool . . .
you do a bool check each time you do the interaction tho
while delegate assigned once
anyway is there a saner solution?
a simple bool check does not waste performance. it's literally a bit check . . .
delegate type stuff might make more sense from a code architecture point of view (maybe) but yeah not for performance
wouldn't you have to check if the delegate is assigned?
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
well, by default, most people would check the delegate before using it to avoid the error, no?
You would be unassigning from the delegate once the tip is shown?
So it’s only shown once?
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
no that’s psychotic
I don't know what to do
This will be strictly worse
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
something something branch prediction
Not needing to poll the state would probably be what you'd want but depending on context, it may be more convoluted and better just to have a simple conditional branch. What exactly is this solving? Unnecessary complexity is generally not preferred.
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
You can make a post in #1390346827005431951 with a Code review tag and someone might take an interest to answer you. Should make sure your code is well commented and illustrated with relevant component screenshots probably as well.
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 ?
Canvas has Image component to render pictures.
Im afraid I cant edit the canvas seeing as im working within a prefab
Oh alright, thank you ! Sorry for the bother
Could anybody help me and my friends make a game
!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**
I meant using the whole interaction method as a delegate, not inserting a delegate into it
Is calling a delegate more expensive than calling a method?
I just feel like there should be some way to remove useless bool checks since you know at the begninng bool will never change
buut I see, branch prediction makes it basically pointless
https://youtube.com/shorts/tkmejgelo4M?si=qtvIsQmPzD45Gc50
Anyway to get this merge in unity?
👋 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...
not in default Unity for sure
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.
https://assetstore.unity.com/packages/tools/behavior-ai/hypernav-3d-pathfinding-and-navigation-235638
people ve been doing those at least
huh, the guy developing a zero gravity shooter with proper AI companions and enemies
impressive
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;
Why I can't see the blue surface of the navmesh?
I have gizmos enabled, "show navmesh" set to true, baked the mesh
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?
Can't you just make it a public function and public class?
yes but how do I reference it from a script?Because I need an object for that
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
That is also true
or just use static
you can also make it static
or dependency injection
a regular C# script
and so on
I will try those now
I'd recommend searching it up, these are some basic OOP principles
Especially in C#
exactly
Honestly I can't beleive there are non OOP langs, it would be absolute HELL for me
I love my OOP langs
bumping my question
@elder hearth Would this cause lag?
Why would it?
it creates another script no?
If I have 100 of those it would be laggy?
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
Exactly
how do I reference a GameObject in the Hitbox_Module? Grabbing and dragging won't work, do I use scriptable object?
transform.Parent, GetComponent, etc.
The Hitbox_Module isnt attached to anything
its just there
It will still work
so I use scriptable object no?
No
Ima try then
It calls a reference of it
thanks it does work
That is all guys
thanks
No problem!
Does anyone know a platform for laypeople who want to learn coding to make games for beginners?
Waht kind of platform are we searching for here? Game engines, learning platforms or something else?
Platform for learning to make games and a platform for making games
There are a lot of game engines. Unity is among the better to get started given how much resources about it are freely available online. Unity Learn I have heard is a good way to get up to speed with Unity.
removing the gender from layman feels silly
Aight thx mate
Im very bad at english XD
Lol started with kaplay joined unity now I'm traumatized guys who understands properties 🥀
most active people here probably understand properties, do you need help with them
if so,
!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
Aight I'll try searching the documentation thankies
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
Generate a random number and compare
{
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
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
array -> generate index -> index array -> random non-numeric value
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)
no
I wouldn’t do that. Array is already index to item mapping
oh shit I got confused with this a bit let me brainstorm a bit
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
I mean it would work but is just not required nor is it as efficient
would be more fragile and more work to add/remove elements
!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**
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
You have to use its Rect Transform in order to rotate it there is Rect Struct in Unity you can use in this case
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
The Rotate function uses a 3 axes of rotation system called euler angles
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
I am not really familiar as well to tell you I am practicing a lot and Game Math is hard concept
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
Linear Algebra yes and Boolean Algebra there is also statistics and more its not just linear algebra of course not.
statistics and probability are everywhere in AI like steering behaviours and more advanced systems I think
hello can i send a vid to ask about some stuff and wanting some advices??
it's mainly geometry & math functions as far as I know
And ofc there's physics
Mainly
yes it is unity 2d
it is unity 2d but like ability system
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.
Fortunately Unity does lots of heavily lifting when it comes to physics. There are some strange behavior with it though, for example one time I was making a pendulum using real formulas, and for some reason the system kept gaining small amounts energy for some unknown reason
I can't be bothered with allat
I'm figuring out input system right now and how to control it
Yeah the answer I got was pretty much "Unity is not meant for perfectly real-world physics simulation"
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;
how are you verifying that "grabber" isnt null, what even is grabber in this context?
If the error says grabber is null then it's null
is it declared as a gameobject?
THe first line isn't returning null
But the first line isn't returning null
can you answer all the questions, how is grabber declared?
is it "public GameObject grabber;"
its is Transform grabber;
Which line? The if statement or the parent assignment? Neither of which confirm grabber is assigned
this.gameObject.transform.parent = grabber;
That line runs completely fine if grabber is null
Through code, an interface to be exacr
You can assign a parent to null, that's how you unassign a parent
exact *
Grabber is null
I can?
Oh
i did not know that tbf
It is just Transform.Rotate.
RectTransform inherits from transform. It's the same as adding that value to the euler angles of the transform, nothing fancy.
Thats likely a side effect of floating point imprecision. Small errors add up and some energy might be lost or created from nothing
Not sure if the other physics backends are better at that
But maybe
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"
Oooh that would explain it
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
So it does work like I thought huh
I was afraid that this line would immediately make the function count as "complete"
Nope, it just pauses for that duration
I see
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...
mine does not have this
i cant connect the bullet spawn to the bullet
READ the error and observe whats missing
See how it even told you its on line 21?
Once fixed it should recompile and show changes you made
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?
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 😭
The first two lines are only necessary for older versions of Unity. It used to not be possible to serialize generic types (save for some exceptions, like List<T>) directly
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);
First line is correct! Second line should use rb
You are trying to use the type name
How do I pass a parameter from editor then?
i'm not sure what you mean by "from editor" here
your example shows you invoking the event via a script
OHH i get it now that you mentioned that ty!! it works perfectly now
first line (line 28) defines a new variable with the type RigidBody with the name rb, the second line (29) should then edit the linear velocity of that variable like this: rb.linearVelocity = velocity;
fab ty!!
If needed brush up on c# syntax
Rigidbody is the concept of a physics object; rb is a variable containing a specific physics object
yeah i definitely need to work on it more
that makes sense
ty
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
do you mean just opening the c# scripts in vsc or smthin without unity open?
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
what are these warnings?
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
sometimes the unity engine just sends random errors, if it compiles u can just ignore it
Alright
scripts are part of unity, if youre making changes to scripts - youre making changes to your unity project
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
Update runs once per frame. If you don't want to do it once per frame, don't do it in Update
instead, do it whenever you actually want to be adding 1
"each time a condition its true" is really vague
example i have
if (isAttacking){combo +=1;}
how often do you actually want that to happen?
You need to provide more context here
Maybe show your code
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
So when do you want to add one?
When you press the button?
There still isn't enough information here for me to give you practical advice
is it possible that your cloning a bullet thats acctualy in your scene and not a prefab?
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
There's a lot that's problematic here
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
ohhh i think thats it yes
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
thx
Hey guys, do you know why I can't drag and drop mp3 files into Unity?
What happens when you try? And where exactly are you dragging them?
my cursor turns into a prohibition sign, and I'm dragging and dropping from file explore
you cant drag from zip files
Where are you trying to drag TO inside Unity?
does it happen with other files?
its not in a zip file
Are you dragging into the Project window, or elsewhere?
yes
I'm trying to put it into a folder
yes
yes
well people have gotten that before but i don't remember what it was or how to fix it
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
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>();```
Can you explain what you mean by "doesn't work"?
can you be more specific about how it doesn't work
that works
ty
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
It's because it's not an array
You can only use this syntax for structs with arrays
You need this:
MonStats stats = monPark[monParkIndex];
stats.monsterName = "";
monPark[monParkIndex] = stats;```
when you're asking about errors don't rephrase/retype the message, copy and paste it directly. you can lose info retyping it
It would also work with your current syntax if MonStats was a class instead of a struct
My IDE is in french
But the problem with trying to do this with a List is that the indexer returns a copy of the struct
https://unity.huh.how/compiler-errors/cs1612 further reading
so modifying that copy would not do anything - and the compiler gives you an error instead of letting you footgun yourself.
So what do you recommend me do? I use a list cos I want the size to be basically infinite without having to rely on an array. Should i make a class?
I showed you above how to do it
As for the question of class vs struct - I don't know enough context about your code this to answer that really
ho mb didn't see
How should I start to learn c#
Thank you so much😭😭😭😭
https://www.w3schools.com/cs/index.php
w3schools has a very simplified introduction of concepts
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
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
i change it in Player Settings
but, how is the new input manager?
like, the code
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?
it runs when you jump up because you set smashing to true when space is pressed (which I presume is jump)
right after, in the same frame still, you call smashAttack()
how you check the ground ?
you should keep track of "did the player jump already?"
If they did, only then, when grounded becomes true again, you smashAttack()
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
what's the problem specifically?
how mouse hovering works
i found a solution but it only worked for text which is a ui element
you're asking how to know if the mouse is hovering a gameObject?
yes
IPointerEnterHandler should be your answer then
https://docs.unity3d.com/6000.4/Documentation/ScriptReference/MonoBehaviour.OnMouseEnter.html
there's this also, depending on what you're trying to do
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
IPointerEnterHandler only works on UI / Canvas by default otherwise it needs a physics raycaster on camera
otherwise you can just use a regular 2D overlap point
any kind of collider would work
or is it a spefic component
which one ?
for overlapoint Physics2D works for 2D collider
Physics class with 3D
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?
Configure your IDE so you get code highlighting and proper autocomplete before doing anything else
!ide
If your IDE is not autocompleting code or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Because you have an error in your code and you can't even see it
okay thank you, will take a look 🙂
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)
📃 Large Code Blocks
Use links to services like:
https://pastes.dev/
https://paste.yunohost.org/
https://share.sidia.net/
https://paste.ofcode.org/
https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
cheers, i setup vscode and found the errors. All working now 🙂
Ideally Visual Studio I think -- unless you have hardware restrictions
Whys that? 👀
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?
the left is the animator window, while the right is the animation window. two completely different windows
oh i see, how do i open the animator window? i do not see that in the dropdown
use the Window menu at the top rather than that context menu
I have this script database where I store all my scriptable objects. Can I change them at runtime? like sprites and all?
thanks, got it 🙂
this is really not enough info to go off of. but 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
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; }
which part of what i said are you not understanding?
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
Then Idk I'll figure something out then
They aren't meant to be changed during runtime. They are mainly used for immutable data that many objects reference to save on memory and avoid repeated data/values . . .
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 . . .
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.
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Also, literally, top 10 results in Google.
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
Most of it still applies with minor changes. Mostly api renames or method signature changes.
Depends on what topic exactly you're I terested in. They can't cover everything. That's impossible.
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
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?
After you have a good understanding of C# I highly recommend checking out a youtube channel called "CodeMonkey" he has a 10 hour course that boosted my skill and confidence an insane amount
what do you mean by "from the scene view"? the game view isn't affected by the scene view
is your camera set up correctly?
What im seeing on the scene is not what im seeing in the game view
I dont know what camera means
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
this is normal and supposed to happen
so where do I go to fix it
the Camera is the thing rendering the scene into the game view
theres this part saying main camera
that's an object and it has the Camera component
but i dont know what im supposed to tweak to change the view
if you select that object you can see a preview of what the camera is looking at
change the size of the camera
so theres no auto scale to the objects ive already set up?
fischer random? 😄
not sure where you're getting that from
what do you mean i just asked a question
i didnt get anything from anywhere
auto scale isn't a thing
you'll understand when your a bit more comfortable with unity cameras but that would be super hyper specific so no
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
(would not be fov)
No i have no idea why the queens and rooks swapped lol I just noticed when you said
😄
how do I do this? i clicked run then i changed the size of the camera to 10, that worked great. Then i stopped it and changed the camera size back to 10 and then when i run, its ruined again
if you change it in playmode, it won't save
as in the size changes again when you enter playmode?
start with size 5 then change to 10 in play mode
not sure what you mean by that
start with size 10
it shows 10
If i change it to 20 now then it shows this
when I start with size 10
while in playmode with this issue, how does the camera look in scene view
this is what im changing on the camera is there another section im supposed to change
this should be it
scene view is fine
as in, the camera frame encompasses the entire board?
yes
actually it zooms in to the perfect spot on scene view with camera size 10, was a little small on 5
make sure you only have 1 camera in the scene, i guess?
but game view doesnt change based on the camera size setting
but when i change the size inside playmode it fixes the problem
this is all I have
so make sure those other objects don't have Camera components
which means?
The king and queen are on the wrong colours
yes
which part of that are you asking about?
have you gone through unity essentials on unity learn
you said to make sure they dont have camera components
do you know what a component is
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
so do you know what a component is
the parts on the right?
sure, i guess
try searching for t:Camera in the hierarchy, to confirm there's only one camera
I think you need to do a tutorial on the unity editor itself 😄
Hiearachy, inspector, components, prefabs, instances, project window, scene view, game view, gizmos etc
thats it just the one
make sure the scene is saved i guess
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
X and y numbers individualy would be fine too
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
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
Buy a new monitor for each scene in the game 😄
kind of makes it seem impossible to develop for different screen sizes if theres no auto scaling mechanic
there is but it gets a bit complicated 😅
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
well it doesnt matter how complicated it is it needs to be done no?
maybe one way around it could be to have a background instead of trying to trim the scene for the chessboard to perfectly fit the screen
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);
}
;
Go for making Chess game is insane👀 complexity systems is not beginner friendly
Now i wonder why you write {} instead of ()
I think your code in written wrong. And yes there function with multiple parameters and you can make the parameters in multiple lines
not like that, no. the {} to set members is for constructors
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
I see. I'll definitely do that then.
Thanks for the help.
also just btw, types should be in PascalCase, so keyword there should be Keyword.
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()
that seems normal
that was just a little typo, no worries there.
you still havekeywordin this newer snippet
honestly i didn't even catch the lower case k. i was wondering why it was throwing an error
If your IDE is not autocompleting code or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
yeah visual studio like 50% of the time isn't throwing errors actively for some reason
ever since i started using the 2026 build
Also just a random observation take it or leave it but you could potentially automate those long lists of strings
regex time wooooo
Automation? are you thinking of like using string public methods?
I mean not specifically, I just mean your variations of those strings could be consistently made via code
could just be like /anti[- ]?hero/i
Yea I’m wondering now if I can just yoink the source code from Lichess, implement it somehow, and modify it
im not regex pilled but if you force lowercase whatever the input is there's only 3 variants right?
- no space, no hyphen (antihero)
- space, no hyphen (anti hero)
3 hyphen (anti-hero)
probably not no
Why?
it would be heavily intertwined with lichess's code and also it's not made in c#
well, it is open source
That would be cleaner but sadly i have a boolean as well which is called isNumbered. Basically you add a number after the keyword and it can output even more possibilities.
It’s open source and free to use, the entire thing is on github
It's hard to briefly explain but it's already abit messy
my comment doesn't imply otherwise
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
if you don't have much experience making chess sounds like a nightmare
(at least the overall structure, not the specific logic for each piece)
Well I have a pretty complex game to make, implementing the rules of chess seems brutal
just so you know what's going on as a whole
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:...
as a beginner, understanding a whole foreign codebase to a degree you can integrate it with your own systems would probably be harder
Might as well code fishstock while you're at it. 😄
Ideally I would isolate the part about the game actually being played
What ai stuff
I don’t need an engine to analyze games, but that’s not that hard anyways
a chess bot
Maybe some chess bots have parameters built into them for you to modify.
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 
chatgpt chess
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?
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
i just use OnCollisionEnter and OnCollisionExit functions in PlayerController script with the collider of the player and ground with ground tag
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
that is kind of what I tried to do with the bool smashing, but i am not sure how to keep track if the player has actually jumped up, is looking for a negative velocity a good solution to that?
https://codeshare.io/5Dw7EW Laddy's can anyone help me figure out why screen positions break?
btw on line 122, mouse delta shouldn't be multipled by deltatime
anyways which line/method has the issue?
Ohh, okay, Ill change that, ty
void ResolveShot(bool won) Distranced always calculates to about 200~
can anyone tell what is the issue?
It used to work, but i changed the camera angle a bit and now it kinda all just goes to that
have you tried logging reticle.position and enemyScreenPos to see if they're the values you expect?
(also shouldn't this practically be in world units)
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
screen units are in pixels, the same physical distance could have different screenspace distances for monitors of different resolutions
so are those the values you expect?
Huh, so how would I do that right?
90~ give or take 20
convert the reticle to worldspace and get the worldspace distance
you expect all 4 values to be 90?
also shouldn't you be using anchoredPosition for RectTransforms, rather than position
No, just the difference
so what do you expect the enemy screenpos and reticle screenpos to be
and do they match what the logs say they are
Well i tried, but that kept failing, not sure but i think its because of like moving of the reticle
are you moving the position or the anchoredPosition?
(when you tried anchoredPosition)
Enemy is right, but the reticle isnt really its like 200 off
try using anchoredPosition i guess
and make sure you're also using anchoredPosition when moving it
position i think, I dont remember completely, and i cant check cause i wasnt using git back then, only started 2 days ago
you can try to read screen resolution and use it as coeffs
I was doing something like that successfully
no idea what is the best way
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
in scene the camera should only show the inside of the border but the outside of border is also shown?
the game view seems to be aligning with the camera edges just fine?
the scene view should not be affected by the camera setup
anything ?
i know i even tried cinemachine camera & cinemachine brain but after the game view disappears
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
i know but the camera position is what is important i change it different aspect ratios . it only show the middle scene?
what middle scene
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
this ?
the middle of the scene?
Thank you
when ratio is change .you see it in photo
what's the issue though
the camera range
this is how it's supposed to work
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?
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
where's the issue
thats the issue the position of the camera is concern as it also show it in different ratio
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?
ok you player 2d game the camera only show the player and border behind it right ?
that i wish to do
that's.. not coherent
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
the border on playes's left side
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
is this about making the camera not show outside the level's border?
(btw you can drag on those int fields, that would probably be easier to test)
trueee ty
that is very fair, i gotta set that up
i assume voxelCount is Vector3(slice, slice, slice) and voxelSize is Vector3(bigCube/slice, bigCube/slice, bigCube/slice)?
correct, sorry for not sending that
all of this is vector3.zero with no rotation or scale
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
i see
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
yeah you'd shift everything by -bigCube/2 or -count*size/2to get it to be around the origin
🙏 bless you
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?
Any git interface you want
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.
i just use the CLI directly
Fork is great (app)
How would I rotate a transform into a random consistent direction indefinitely?
This is how you rotate something indefinitely:
https://docs.unity3d.com/560/Documentation/ScriptReference/Transform.Rotate.html
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
This is how you pick a random direction:
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Random-onUnitSphere.html
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
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.
won't I get valid consistent rotation if it was a non normalized vector anyway
You're gonna need to define what you mean by consistent
Consistent speed? Consistent direction? Consistent acceleration?
won't it fit all those 3?
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.
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?
you don't have to use an array, there's several ways to store multiple values
How
if they have rbs you should use rb.position/rotation though, not transform.position/rotation
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?
you could have each object have its own field, you could have an array, you could have a list, etc
well you want it to happen to every item, don't you
Yes
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
Don't know how that would be inaccurate by any means. If you are running out of space on the stack, you probably have too much recursive calls in it. Impossible to tell what exactly is wrong with your implementation without seeing the code. It could be something wrong with the termination condition or just the task requiring too much space to fit into the stack.
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
Stack overflow literally means that you are running out of stack space. Most of the times the reason that happens though is due to something wrong in the code that just fills up the stack indefinitely
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
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 😅
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
Use a stack or queue instead of recursion
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
does that take into account the margins as well?
No idea, 
welp i geuss we will see in a moment
doesn't need to be infinite to fill the stack, just needs to take up enough space on the stack
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
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.
for depth-first stuff you need something FILO, that can be just a Stack object or the callstack - that's what the recursion achieves
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
i vaguely recall you have to check if element explored before looping?
gonna have to think about that for a bit
Now it's inside the loop. Either one works I believe. I like this one better since it doesn't need to iterate over the elements that are already explored
yeah it'd reduce a lot of looping
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
Would it be common for not yet explored to just be some hashset that i chuck them into for comparison?
heard heard
its 1:30am so lemme finish my coffee and then i might mess with this, tyty
It works now?
odd
Which would? Having the check before the foreach instead of within it or having a check to begin with?
I think this is better. You avoid adding elements to the stack if they are already visited
(If the other option was to add them always and then continue if the element we pulled from the stack was already visited)
thats not neccasarily viable though right? depending on the context?
Yeah that's what I have thought. I have seen a lot of examples do it the other way like this:```py
stack = starting element
while elements in stack:
if neighbour explored:
continue
element = get and remove from stack
#do something with the element
mark element as explored
foreach neighbour of element:
add neighbour to stack
Ello im new to coding guys I dont know where to start
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
check the pins for beginner c# tutorials and once you've learned c# enough you can start learning unity at learn.unity.com
wdym first pass? as in breadth-first?
aww thank you , btw is there any trading course offered here?
wdym trading?
I don't understand the example. Flood fill does do the if neighbour explored check multiple times for most cells no matter how you implement it (if that is what you mean?)
trading...
trading what?
you mean programming a trading system for your game?
there are probably tutorials for that on youtube
no stock and forex market one
You're really going to have to define what you mean by that
This is a Unity server
im new to that too
and what's ut for
sir this is a wendys
New to defining things?
uhm isn't unity server's all abt learning new things together
Unity game engine, just to be clear
It's about Unity
ohhhh game engine
got it
I guess I'm expecting way too much out of someone named "Elon"
i was finding the server i sold in 2021 named unity
uhm u can say that , i dont feel bad
like in this example, would my code ideally do
0: White Tile, just go to next
1: White Tile, just go to next
3 (i forgot 2): Green Tile, add 1 & 7 to stack (dont add 4 because we are about to go to it?)
@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?
A basic ability to read might be useful.
read language like c++ and python am i right?
Wouldn't your flood fill start at tile 3, not tile 0?
So take some time, work your way up to that, then try programming
okk , so what's needed to create ur own coding language and ai agents ?
physics? chem ? mayhs6?
Different server, but maths is quite important