#archived-code-general
1 messages · Page 131 of 1
That actually worked, many thanks!
new smaller issue, unsure of how to actually check for which layer is being hit in the if statement
cause i cant use GetMask on my layermask to define which layer is which from my raycast.
if (hit.collider.gameObject.layer == theIndexOfTheLayerYouCareAbout) {
ill try that
you sir have made my day
🫡
absolute legend
How can I print out all scripts that are using a function
void Function()
{
print(All Scripts that call "Function")
}
so lets say I have class A with a variable of int speed which has a value of 5. And Class B that inherits from Class A. How do I make it so that inherited classes also have the value of the variable from the class they're inheriting? In this example, Class B's speed variable would also be 5 similar to Class A.
Make the variable public or protected.
Oh yeah protected works best with what I'm doing
I assume getters and setters might also work
Depends on what you're trying to do overall.
Hi. One question, what would be the best way to have like 5000 bullets spawned and moving and checking for collision without tankind performance please? Like for a fast shooting weapon
idk if this would be the best solution, but you could create a new material and then assign it to the cubes with code
or you want it like random colors?
but like, how do you want to colour it?
like, just a single color for everything?
hmm then maybe vertex coloring would be the best solution, but I'm not 100% sure how it works😅
What were your search terms?
Mine would be along the lines of 'unity how to set vertex colour via code'
Can't say, don't have enough info
If you create the meshrenderer from scratch via code, then your material + texture will need assigning correctly at run time.
If you already have a sphere, with a material and texture, but manipulate it at runtime.. I would expect the material/texture to display regardless.. just if it's UV'd it'll be messed up
Anyone here who can help me out with proper frame pacing
Achieving smooth and consistent frames is quite challenging haha
Profile, profile, profile... on the target platform
Doesn't really sound like a code issue.. unless you've already narrowed it down to your code causing the slow downs
Hi everyone, I asked this last night in the animation chat but since I never got a responce I was wondering if I should also ask here. I'm looking to work on some animations for some machines and my player characters mechanical armor. However since I'm a programmer, and not really well versed in rigging and animation I was thinking of just doing all "machine-based" animations through script, (like a hydraulic piston in a joint setting its position and rotation through script as the body moves). Is this a feasible solution or is scripting too slow for this on the large scale, that something like the animator might be better off with.
I've written IK before through scripts so I'm thinking of just doing things like that but as a global solution for all mechanical things if that makes sense
100% it's going to be a lot better with an animator... you can do it via code though, but it will be very time consuming depending on amount and complexity of the animations
No it's not about the performance. I achieve proper 60fps on most devices or else I lock the framerate to 30 using application.targetframetrate
My issue is more about minimising stutters. And I really need a long dedicated talk with someone man
stutters happen because of...... performance
Lemme elaborate
Loading a prefab that isn't already in the scene can cause a stutter
As @trim schooner says, the profiler will show you the frames that typically use more resorces and cause stuttering. There is some overhead with the editor running in the background, but usually if its a script issue you will see a large spike on the frame, then you can use deep profiling to find what is causing the stutter
You can have a solid 60fps for the whole game and just one frame where something large happens / or alot of garbedge is collected. which can cause a spike in frame delta time.
Is that your issue?
More about a frame variance thing in my case. My game works on 60fps all the time. There's no lag. It's just about mismatching refresh rate and Target framerate, and/or very small variance between previous and current frames. To eliminate this Unity has the optimised frame pacing for Android which uses Google's swappy. Maybe you'll understand it better if I further let you know more about my issue and the topic
So um, if I play the game at 60fps while my device is working at 60hz refresh rate things are smooth as silk. And once I toggle to 120hz refresh rate, the same 60fps starts to stutter (feels less smooth and sorta jittery)
Now if I lock the fps to 30 with my device is at 60hz, 30 fps feels not so good
I understand there's a difference between 30 and 60 but it can look better
I'll give more information which would convince you
And if I lock the fps to 30 and the screen is at 120hz refresh rate things start to feel alot more choppy
Lemme screen record it
This is 60fps at 60hz refresh rate
There's no frame drop at all, and you may feel some micro stutters in the video if you're really paying attention, just ignore them it's my screen recorder's fault as the game never stuttered at all.
Now this is the same game working at the same frame rate at 120hz display
Look carefully. Do you feel the difference in smoothness?
30fps feels bad at 60hz and even worst at 120hz due to the same reason
Now it can feel better!
isnt int points basicly the same as private int points ?
Yes. If you don't declare if it's a private or a public variable, it defaults to private I suppose
Ok so look at this. This is an old Java game for old Nokia devices, and it's running at 25fps :0
And now this is my game working at 30fps :/
Ignore the fps counter I recently broke it by doing the stuffs under fixedupdate
Fix is, to change the refresh rate of the device to the closest value possible to the capped framerate
But I can't cap the refresh rate to anything lower than 60hz so for 30 fps unity's optimised frame pacing can do the job. It has it's own useless overhead so I don't want to use it for 60fps and above as I can lock the refresh rate to make it look smoother. Is there a way to toggle optimised frame pacing on and off through a script?
Also instead of directly asking the question I wanted to show some states. Idek how old games used to look that smooth at such low frame rates without any special effects like motion blur. I would like to know more about frame smoothing techniques if possible
I was wondering if someone would mind helping me as i got myself in a picke with material.Settexture.
It’s for future debugging purposes
i am trying to add a texture i just created to a material but for some reason it is not working. Setfloat and Setvector work fine for the same material. I have double checked the property reference sting in code and it is definetly correct
mat.SetFloat("_GDTScaleAdjustment", terrain.terrainData.size.x);
mat.SetTexture("_GrassDamageTexture ", image);```
You have a space after the parameter name in the string, is that intentional, or a copy-paste mishap?
@sharp dirge !collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
Hello! I'm working on a desktop companion application similar to shimeji. I have working transparent background, but I don't have any idea on how to interact with UI elements on a windows OS desktop screen.
This is the closest thing I was able to find regarding the topic, but I don't know if this is the correct approach nor do I know how to access these dll files in Unity:
https://stackoverflow.com/questions/73361591/unity-desktop-app-c-sharp-finding-position-of-task-bar-to-align-assets
How would one go about getting positional data on windows UI elements like the windows taskbar, and how would you translate that to ingame world space?
Does anyone have suggestion for detecting if code is running as a part of a unit test or in normal play mode?
i just detect my code in play mode with log(start running) then delete it if it works normally
or you can have some #define DEBUG (preprocessor directive)
I was hoping to find a combo of things that works with what unity does itself, the code where I'm putting is in a [RuntimeInitializeOnLoadMethod]
Hey does anyone knows how to change the global fixed timestep value through script
Saw on git that it had created a scene file "InitTestSceneXXXXXXXX" so this seem to work:
SceneManager.GetActiveScene().name.Contains("InitTestScene");
I actually have a doubt about it. I stumbled across it lately but does it actually changes the fixed timestep value globally (for every scripts using fixedupdate) or locally (for the specific script it's mentioned in)?
public static float fixedDeltaTime;
static means global in this context
Thanks!!
Unity's fixed timestep loop
But also what Steve said
Thanks alot friends!
hi there guys, is it there any way to launch a .bat file inside unity?
dont cross post
idk if you can make a new process in unity
(i know nothing about process in c#, i only know exec of c)
yeah
cross post? sorry but what I would like to achieve is creating a mesh via an external script in python an run it inside unity so I can render it there
cross post means dont post the same thing across multiple channel
aw ok I didnt know
Assuming this is Editor only, the usual Process.Start(path) should work
I placed the bat file inside the asset folder of my project
I made a script in C# trying to open it on Start() but seems like it doesn't work
you're trying to open a C# script?
what does that mean exactly?
nope, a python one
Like open it in a code editor?
no I just want it to run the code
you need to do Process.Start(pathToPython) and include the path to the python file itself as a parameter
i.e. you need to know where your python executable is
not your .py file
but the python command itself
it's the same as starting it in the command line /path/to/python/python.exe myPythonScript.py
I was trying this approach because I have a lot of imports in my python script that are not compaytible with unity
nah just call the python from the batch script instead
oh yeah if you have a batch script already running do that
so? any idea? I was thinking is it possible to just like attach my bat file to an empty game object and on play I say to unity to run it?
comprehension issue 101
sorry Im not native... mmm like how can I run this bat file while play mode is on?
question 1, how do you think you can attach a .bat file to a GameObject?
I dont know xD that's the point, I dont know if its even possible
it's not
why does it need to be on a gameobject?
you already been told how to do it tho..
you can run your python script by system call (?) in start....
Process.Start() ?
question 2. Even if you can run your .bat file and it creates a mesh, how do you hope to import that into Unity?
I already made a script that create an .fbx, that is my problem after I can succeed to fix this
Is there a reason you want to create the mesh in python? Is this a Blender python script?
Also is this something you want to have happen in the game itself, or just in the editor
If thids is a thing for the game, you definitely don't want to be using a Blender python script. That puts a hard dependency on the game user having Blender (of the correct version) installed on their computer.
yes, because the mesh is made by an AI so I need torch and all the other libraries from python
SO... it's blender too?
this is quite a lot od dependencies you will need to bundle with the game
yes, I use blender to export the ply file that is made via AI to an fbx
Wouldn't it be better to do the mesh generation in the cloud or something?
I need to pass some variables to the AI model so the mesh created its always different
Hello, how can I know whether an object is an instance of a certain prefab (in my case I want to know if the object that I'm colliding with is an apple) ?
So?
you would have to store a reference to the prefab somewhre manually. Unity doesn't provide this automatically
a simple cast to apple blueprint?
Actually checking which prefab is the wrong way to do that
this aint Unreal
either check for:
- the existence of a component
- a tag
- a variable on a component
@unborn dagger
Ok thank you
ye damn my head is exploding atm
Question is who'd want to play your game when pytorch and all the dependecies are part of the requirement?
Do you know how massive in size pytorch is?
Can I just attach a script named apple and check if it's there or is it bad code ?
😅
that's good code
ok ty
Another option is to attach a script named Item and give it an ItemType variable and check if the type is ItemType.Apple
its not a game bro dont worry, I like unity as an editor to render the mesh inside it
thank you that's a goo idea
then Process.Start() is the way you need to go for your .bat file
In this case does Unity need to do any of this? Why not write a batch script that:
- calls all the python crap to generate the FBX
- Runs your Unity game with the FBX as a command line parameter
and just set the unity game up to read the Fbx directly and display it
THen the unity thing doesn't need to know/care about python or torch or anything
ye I was thinkig something like that, like running externally my script and just importing the mesh via script when I need to
but then I need like a script to run unity and the mesh generator toghether
yeah that's the batch script
ye sorry I read it wrong
ok thx for the suggestion
mmm the cool thing inside unity was like I create a UI that like on click makes me the mesh and rend it in realtime :C
This is my code for aiming in my 2D unity project (https://hatebin.com/qvpehcmcjt). I am trying to do the same thing in Unity 3D but nothing I try works. Either the object doesn't move or it moves so fast it looks like it's flashing. Can anyone please help?
Is it OK to create a new class type for each to categorize/group similar objects?
For example in a game, there are different items/elements.
I can create one class to describe an Element and then several derived classes inheriting from e.g. MaterialElement, FoodElement, etc. or just one class Element and with enum field to group them.
Now, MaterialElement and FoodElement are the same as Element (they don't have additional fields).
If in the future, they have their own fields, do you create spearate classes for each or put all fields in the root class?
Personally, I do not like to create extra classes for each when I doubt if it should be.
It is worth noting, these classes are data structures (data only)
ok it works!! bat file launched
Derived classes
Once you need more properties you just add them to the classes that need them
Hey peeps, this code
if (sun.elapsedTime >= (time * 4) + .1 && sun.elapsedTime <= time * 5 && currentskybox != SkyEarlyDusk)
{
RenderSettings.skybox.Lerp(SkyAfterNoon, SkyEarlyDusk, .5f);
currentskybox = SkyEarlyDusk;
output("Skybox Changed to edusk");
}
isnt working correctly the if statment works and runs the code within it at the correct time, however the skybox isnt updating
RenderSettings.skybox.Lerp(SkyAfterNoon, SkyEarlyDusk, .5f);
is the line that changes the skybox material and then
DynamicGI.UpdateEnvironment();
is used to update it (from what iv read in the docs)
any idea why the skybox isnt changing?
That will set the skybox to halfway between noon and dusk. Is that intentional?
im trying to transition from one sky box to another with some blending so it looks more smooth
https://gamedevbeginner.com/the-right-way-to-lerp-in-unity-with-examples/ <-- applies here as well
You need a variable that changes with time, something like this:
transitionTimer += Time.deltaTime / transitionSpeed;
RenderSettings.skybox.Lerp(SkyAfterNoon, SkyEarlyDusk, transitionTimer);
and you have to change the logic so that it runs every frame
I'm trying to add a wheel collider to a car I made, but the wheel collider is perpendicular to the car's wheels. Anyone know how to fix this?
ty
screenshot
show gizmos as well in local space
also not really code related, should be in #💻┃unity-talk
its rotated 90 degrees
it should be 0
when it was at 0 rotation it also wouldnt work
wdym "woudln't work"
its probably the parent its nested in
oh ok
I tried rotating the parent and the wheel collider was still perpendicular
idk try making a new gameobject only with wheel collider see which direction its pointing
I've used wheel collider like twice
OK, so you say derived classes for each even if they are empty?
What about if several derived classes have one same field? again inheriting?
public class ElementDefinition: ScriptableObject{
public string Guid;
public string Name;
public Sprite Icon;
public ElementGroup Group;
public ElementType Type;
}
public class FoodDefinition:ElementDefinition{
public int Energy;
public Receipe[] Receipes;
}
public class SeedDefinition: ElementDefinition{
}
public class MaterialDefinition: ElementDefinition{
public MaterialGroup MaterialGroup;
}
//...
Also, sometimes it is hard to categorize them. For example a seed can be a food or not
Isn't it more flexible to put all in one place?
public class ElementDefinition: ScriptableObject{
public string Guid;
public string Name;
public Sprite Icon;
public ElementGroup Group;
public ElementType Type;
public bool IsEdible;
public int Energy;
public Receipe[] Receipes; // for foods or crafting materials
public int Temperature;
}
I hope this is the right place to ask this but Im trying to use unity multiplayer stuff. I cant figure out how to use the callback function onClientDisconnect. Like how do I actually use code when someone disconnects
Thank you
does anyone know if there is a photon discord? im kinda stuck on this small thing in my multiplayer game
because i cant find one
so i'm havning some problems with this script:
if (Input.GetKey(crouchKey_))
{
crouched = !crouched;
}
if (Input.GetKeyDown(crouchKey))
{
crouched = true;
}
if (Input.GetKeyUp(crouchKey))
{
crouched = false;
}
if (crouched)
{
transform.localScale = new Vector3(transform.localScale.x, crouchYScale, transform.localScale.z);
}
if (!crouched)
{
transform.localScale = new Vector3(transform.localScale.x, startYScale, transform.localScale.z);
}
basically crouchKey is shift and i want it so that you crouch when you hold the button, while crouchKey_ is a button on the controller and i want to make it so when you click you start crouching and when u click again u stop
Image
it kinda works (once every three times i click) but is super buggy and i can't
and also i'm having problems with this other method: it will correctly debug when crouched is true but it will never put the state to crouching
Debug.Log(crouched);
if (grounded)
{
//Crouching
if (crouched)
{
state = MovementState.crouching;
desiredMoveSpeed = crouchSpeed;
}
//Sprinting
else if (Input.GetKey(sprintKey) || Input.GetKey(sprintKey_))
{
state = MovementState.sprinting;
desiredMoveSpeed = sprintSpeed;
}
//Walking
else
{
state = MovementState.walking;
desiredMoveSpeed = walkSpeed;
}
}
any help would be appreciated, thanks!
You should post your !code on a paste site, so we can see line numbers and there aren't formatting complications (like Discord turning your _s into italics here) 👇
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
alright wait a sec please i forgot
if (Input.GetKey(crouchKey_))
crouched = !crouched;
This will toggle crouched between true and false each frame for as long as the button is held. Since you want it to toggle only when the gamepad button is pressed, you change it to a Input.GetKeyDown() instead - that is, "toggle crouch state when button is pressed" rather than "if button is still pressed toggle crouch state".
i tried but that sadly didn't work at all
What are the symptoms of it not working? I don't think it'd be possible for
if (Input.GetKeyDown(crouchKey_)) {
crouched = !crouched;
}
to not set your crouch state correctly 🤔
when it's getkey it jitters a lot but it works (although the method where the moving state should change doesn't work). I'll now try to put getkeydown instead of getkey and report what happens
ight so what happens now is that it works and doesn't jitter anymore (i had to change a bool in a method above that was causing an overlap of things to do when crouch key is pressed). now the movement state also goes to crouching, tho i can't walk, i can only jump somewhy
https://gdl.space/raqanahaqa.cs @wide terrace
Like when crouching you can't move, only jump?
Yeah just digging to see if I can spot anything 😅
Just to be sure - crouchSpeed is set to something other than 0 in the inspector for this component?
yup it's 0.5
sorry for pinging ya, just wanted to make sure you knew i was still here
🙂
Nothing immediately jumps out at me - you may need to start sprinkling some Debug.Log()s around to try and narrow down the problem. Maybe starting with the end of the movement process here, in order to ensure the correct moveSpeed is in fact getting all the way to the AddForce() call. To that end, I might slip one in MovePlayer() like
if (crouched) {
Debug.Log("MovePlayer() crouched with moveSpeed " + moveSpeed + " in direction " + moveDirection);
}
That way, if it logs an incorrect value for moveSpeed, we'll know the problem's somewhere in the prior speed handling code. If it is correct, then a proper force should be getting applied - so it might be that crouchSpeed needs to be bumped up to overcome friction, or perhaps crouching is sinking your collider into the floor or some such.
thanks a lot I'll try more debugging
im making a fps game that uses projectiles as the bullets how do i make the enemy take different amounts of damage based on the type of gun im using
put a damage variable on the projectile script
have the gun set it when it shoots the bullet
so public float damage;
sure
if i run into my enemy it stops following me and is repelled by me
how can i fix this is my enemy code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class Enemy : MonoBehaviour
{
public GameObject player;
public GameObject effect;
public float damage = 10f;
public float enemyHp = 50f;
public float previoushp;
void Start()
{
previoushp = enemyHp;
}
void Update()
{
gameObject.GetComponent<NavMeshAgent>().SetDestination(GameObject.Find("Player").transform.position);
if (enemyHp < previoushp)
{
previoushp = enemyHp -20;
}
}
void OnCollisionEnter(Collision other)
{
if (other.gameObject.tag == "Player")
{
Player player = other.transform.GetComponent<Player>();
if (player != null)
{
player.TakeDamage(damage);
}
Debug.Log("Player HP: " + player.hp);
}
}
void Die()
{
Destroy(gameObject);
}
public void TakeDamage(float amount)
{
enemyHp -= amount;
if (enemyHp <= 0f)
{
Instantiate(effect, transform.position, Quaternion.identity);
Die();
}
}
}
holy lord cache that NavMeshAgent first of all and also store player transform reference in start , do find by tag at least
also make a video of what u mean..
repelled by me and stops following doesn't come clear in this code
nvm i fixed it by adding walls
there is, I'm part of it. Just google it I guess.
witch sprite mesh is most performant
Helloo, I am in need of some help cause I am really lost. I've just made a simple Highscore Table on a scene besides my already existing game scene, where I wrote a code so it saves my highscore.Now my problem is, that I do not know how I should combine these two out, like for example in the game or something I write my name out, and after I make a new highscore it should be saving it to the highscore table, how can I do that? Here is the highscore table code: https://hatebin.com/egyclkjdgn , and here would be the game code: https://hatebin.com/ihttkildzv
Guys why is my raycast so skewed?
Here is the script:
{
Ray ray = new Ray(transform.position, transform.forward);
if(Physics.Raycast(ray, out hitInfo, range))
{
if(hitInfo.collider != null)
{
if(hitInfo.collider.CompareTag("Zombie"))
{
Destroy(hitInfo.collider.gameObject);
}
}
}
}
private void OnDrawGizmos()
{
Gizmos.DrawLine(transform.position, transform.forward * range);
}
dont you think it would be a good idea to make Highscores serializable? Also why are they sub classes of HighscoreTable?
I'm putting it on the main camera
DrawLine takes 2 points
Even if the drawline is broken the actual raycast is very broken
you’re supplying it a direction
Like it detects before it hits
I don’t know what you mean by this
I will provide a demonstration
Welp, I am quite a beginner in Unity so I do not know much what I am doing xD. In the Highscore Script I have this function AddHighscoreEntry(fscore, fname); , I think I just have to somehow be able to use this in the Game Script, but how do I do that? Like use a function from another Script?
replace the DrawLine with DrawRay https://docs.unity3d.com/ScriptReference/Gizmos.DrawRay.html
when should i use structs instead of scriptable objects
those are 2 completely different things
Trying to answer it would be like trying to answer when you would use a hammer instead of a car
got it
oooooooooooh
I think I got it
It isn't ignoring the trigger collider
That i have on the zombie
this is a pretty brief video showing one of the uses of scriptable objects https://youtu.be/lJxy3oTZeCs
Btw how do I get a physics raycast to have ignore triggers but without layermasks
ive used them before so i guess my question is what is the use of structs
I know
I meant in the Physics.Raycast function
Like in all these 16 options
There isn't one where there is the querry interaction but no layermask
I don't want a layermask
you’re already using a layer mask
wrong overload but the general idea is still there
so I just add the layermask and set it to default?
you can
The main thing that structs have going for them is that they are value types. imo they’re better at storing data since you can’t accidentally mess up the source but that’s mostly my use case with them.
ty
here’s a video explaining it pretty well: https://youtu.be/XSUBp-EZhBE
Hello there, I am implementing a random card spawning / selection system and the current algorithim I have has a major problem which Im going to describe. So my algorithim should generate a specific / special card if the player does not have it already and it also needs to make sure that the spawned cards do not spawn more than once (cards can not be repeated). Both things work fine, however my only issue is that the assured specific card is always spawning at the index 0 of my list, how can modify my code so it can spawn at a random index?
//Generate a random relic keeping in mind that they can not spawn more than once on the same round
private void GetRandomRelic (byte playerIndex, RoundAttributes.roundContents roundContents)
{
PlayerBuffs player = playerIndex == 1 ? player1Buffs : player2Buffs;
RelicData relic = null;
for (int i = 0; i < 3; i++)
{
//Checks if the player already contains this relic, if not , then assure its spawning
bool isEvolutionRelic = !player.relicsInUse.Contains(player.skillsInUse[player.skillsInUse.Count - 1].relicForEvolution);
if (isEvolutionRelic && !player.randomPickedRelics.Contains(relic))
{
relic = player.skillsInUse[player.skillsInUse.Count - 1].relicForEvolution;
}
else
{
// Generate a random relic that has not been picked yet
do
{
relic = cardData.relicData[UnityEngine.Random.Range(0, cardData.relicData.Count)];
} while (player.randomPickedRelics.Contains(relic) || (isEvolutionRelic && player.relicsInUse.Contains(player.skillsInUse[player.skillsInUse.Count - 1].relicForEvolution)));
}
}
player.randomPickedRelics.Add(relic);
}
This is the code I'm using
AAGH, I don't know where to ask, I know this isn't probably a good place for this, but I'm going crazy, is there a way to override this limitation in visual studio?
Don't warn me again button?
that will make this go away, but not scan the project
I want it to override this limitation and scan the project anyway
I wasn't clear, true
I mean, the project is like 60gb so I can't blame it, but I really was hoping it's possible
Hmmm, this has never happened to me before tho, but have you messed with the default settings of metadata in editor settings?
Also, why is it that heavy?
Have you tried deleting and regenerating library folder?
it's a project that contains like 6 different projects, is i think 3 years old, and in hdrp (so everything high quality)
Why would you have 6 projects into a project....
Lmao, that's the problem then
just cloning the repo and opening the project (couple of hours) brings it to 60
Having multiple projects inside a single project will increase the size drastically
yea, you tell me
Yeah, library folder stuff
Im not sure if there is a workaround to splitting all those projects in different folders respectively
I'm not sure what this code is doing, but just from your description, I'd roughly do this:
List<Cards> cards = player.possibleCards;
cards.Sort((card1,card2) => Random.Range(0,10000);
if (!cards.Contains(specialCard))
{
cards.Insert(0,specialCard);
}
player.setCards(cards);
or something along those lines
not an option :/
only overriding this limit is an option for me
Ah I get your idea, that should work, thanks
Hmmm, I guess there is a way for asigning a solution for each folder (project) inside your projects folder container, I have no idea on how to achieve that, but that should be the way to go if it happens to be possible
I'm getting some weird 2D Rigidbody interactions wherein a player won't be knocked back in the X axis at all, but will behave just fine when being knocked back in the Y axis. An enemy interacting with a trigger seems to work just fine in all directions.
the knockback code:
public void Knockback(float power, GameObject origin, GameObject receiver)
{
Rigidbody2D rb = receiver.GetComponent<Rigidbody2D>();
Vector2 direction = (origin.transform.position - receiver.transform.position).normalized;
rb.velocity = Vector2.zero;
rb.AddForce(-direction * power, ForceMode2D.Impulse);
}
on that note: would it be better if I didn't use GetComponent for this and instead just passed the rigidbody as a function argument?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed = 5f;
private Rigidbody2D rb;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
Vector2 movement = new Vector2(horizontalInput, verticalInput);
movement.Normalize();
rb.velocity = movement * moveSpeed;
}
private void OnCollisionEnter2D(Collision2D collision)
{
// Check if the player collides with objects tagged as "Obstacle"
if (collision.gameObject.CompareTag("Obstacle"))
{
// Calculate the desired movement direction
Vector2 movement = rb.velocity.normalized;
// Reverse the movement direction to avoid the obstacle
rb.velocity = -movement * moveSpeed;
}
}
}
my player won't collide with rigid body kinematic objects
What does your player have. A rigidbody or a character controller
- Every frame, you're setting the velocity based on your input, in update
- 1 time during the collision, you're reverting the velocity
next frame after collision, it gets reverted back
rigidbody
Check if it's actually triggering the OnCollisionEnter first, then see if your code is just making it seems like nothing is happening based on what octia is saying
also - do the player AND the kinematic objects both have 2d components?
Please don't ask AI..
Okay, how about you try debugging using the link I sent
And in the future please format your code using this
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
also does it work with non-kinematic objects that block? add a lot of mass to them and check
Hey, I'm trying to figure out how to cache the "Debuff ui element" that displays how long the debuff is applied for. The first issue is caching it, the second is making sure there aren't duplicates (to avoid rapid damage spike/dupe debuff elements), the third issue is calling the cache through the StatusEffectDot coroutine since its a temp variable not a permanent one.
rn it does spawn the icons and does apply the correct tick display, but it's unable to limit them/reset pre-existing ones, and tick down the values since I don't know how to access a temp variable externally through an IEnumerator (without converting it to a perm variable? but then would i need a list?)
Hi all,
After copying/re-naming my project, I find the Application.persistantDataPath still leads to the old project's folder structure.
Does anyone know the way to fix this?
Thanks
Same problem as this forum post, but there was unfortunately no resolution there -> https://forum.unity.com/threads/persistent-data-path-not-updating-between-computers.1112617/
where is statusEffectDot? is it in the manager, near applyCondition or on the icon
These are all contained in the same class currently
I have a PlayerDebuffManager that's applying all the states. It's pushing data into the "UI debuff" prefab and trying to track that internally. Like cache it and update it from the current class, rather than have a secondary script on the ui debuff prefab itself working internally
I can paste the entire class online if that helps**
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
wow, I'm gonna blow your mind
learn about dictionaries, and enums
you're repeating a ton of code a lot, you don't need to
O ya i'm familiar with those, just need to figure out how to apply it appropriately since I'm using it in basic ways, and this task seems a bit more advanced
Also, I like to have separate scripts on elements like the debuff icon - keep track of them with a dictionary (key StatusEffectType, value scriptThatControllsDebufIcon)
Have 1 coroutine, running forever, that goes through a list of references to debuff UI icon scripts, and updates them accordingly
could also be a function called in update. Keep the tic counts in public variables in the debuff ui icon scripts, update the image (and time left) from them as well, through a function called by your main script
Ok, i'm sorta following. So I need a class on the debuff prefab itself (the one that spawns into the canvas), then have the dictionary track that
Is that new class ex: DebuffPrefabUI going to read values from the base class PlayerDebuffManager? like some kind of injection within the Start/Awake?
What I like to do for that, is:
Dictionary<StatusEffectType, DebuffPrefabUI> debuffDictionary= new Dictionary<StatusEffectType, DebuffPrefabUI>();
...
DebuffPrefabUI newDebuff = Instantiate(debuffPrefab, debuffContainerAnchorUI.transform);
newDebuff.MyInitializeMethod(debuffEffect, somethingElse);
debuffDictionary.Add(debuffEffect, newDebuff);```
don't bother getting info in the start/awake of the DebuffPrefabUI - too much hassle - just put it in from the class that spawns it, through a function you call
Ok i'll give that a shot. A bit abstract to me atm but I'll figure things out. Also are those two classes in your example or one?
and before that, you just need to check if debuffDictionary has the key for the new effect that you're adding, and if it's not null
if it doesn't exist or is null, do the following code that I posted above
else, access that script, and call a function that will add time to it
and within the update function of that debuffPrefabUI script, change the timer every second (or a coroutine, that could be easier)
also, you might want to put all this image changing in the debuffPrefabUI script, and have it take that info from the debuffManager itself, based on StatusEffectType, from another dictionary there
one class
just showed you what type of dictionary I'm talking about, and how to more easily instantiate prefabs - no need to spawn gameobject directly, you can spawn any component that's on the gameobject, it'll spawn the same, and you'll automatically have a reference to the component you want
would that be inside my playerDebuffManager class, or in the debuffPrefabUI class? It's reading like its in the debuffPrefabUI class
that's PlayerDebuffManager
it's spawning instances of debuffPrefabUI, keeping track of them, and assigning data to them
O gotcha, ok I'll give that a shot
i tried that and i don't think I have anything set differently
would it be possible for me to show u my screen? I could stream screenshot
i am really new to unity
i got it to work but i havre to set player to dynamic
and when i do some wierd stuff happens
No. and please don't send friend requests from here to DM people
How expensive is it to turn a list into a queue?
O(n), you'll just need to add each element
I see
I'm trying to figure out how to best implement an turn order initiative feature.
Got it
if you convert it once, it doesnt matter really. if this is some conversion happening over and over then id be concerned
best thing is just get it working before you try to optimize
plus this list likely wont be that long if its just turn orders, theres not gonna be anything expensive about it
so, I would like to incorporate a speed-based initiative order ala Triangle Strategy (Ie faster characters go more often), with some turn order manipulation seen in games like Honkai Star Rail, where turns can advance or be delayed.
Each unit would have a speed stat base of 100. Their place in the initiative is found by dividing 10000 by their speed, giving an ActionValue average of 100. When a Unit's turn ends, the Action Value of every other unit in the queue would be reduced by the ActionValue of the unit that just had its turn.
Let's take an example, we have Unit A (Speed 80) and B (S 100), and C (S 120).
So, a turn order would look like this (UnitName: ActionValue)
C: 83
B: 100
A: 125
C: 166
B: 200
C: 249
A: 250
When C's turn is concluded, all the other ActionValues for the units in the order are reduced by 83.
B: 17
A: 42
C: 83
B: 117
C: 166
A: 167
And so on. I think this system will offer quite a few fun options for how games will go.
What I'm struggling to do is figure out how to elegantly create the turnorder. What I think I want to do is this:
- Create a number of turns for each unit (say 1000 action points worth of turns).
- When a unit finishes a turn, create a turn at the end of the queue. To do this, I need to find the unit's turn with the highest turncount (or ActionValue), and add a turn at the end based on that.
- If a unit's turn ActionValue changing changes its place in the turn order (such as with an advance or a delay), then this should be reflected in the turn order of course.
- The queue would be displayed in the UI (a number of turns ahead, at least). Changes in the list would be reflected here with an animation.
So, should I go for Queue or List? Or both?
Logically, a turn order seems like something you'd want to use a Queue for. However, due to the manipulation that will happen, a List maybe? I'm conflicted.
I havent played that game but i think i understand what you mean. if you're going to be editing values a lot over the entire collection theres no reason to use a queue because you'll just be dequeuing and enqueuing constantly to keep the order. A list should just be fine
You have to deque the first one, so you can either use foreach to manipulate all the values or implement your circular queue
Good day, Multiplayer Floating Origin. Anyone have experience or willing to discuss ?
{
public class EntityStatistics : MonoBehaviour
{
public Stats stats;
void Update(){
stats.displayHealth = (int)stats.health;
stats.maxDisplayHealth = (int)stats.maxHealth;
}
}
}
for some reason the struct stats doesn't popup in the inspector
This is probably the simplest solution.
public float health;
public float maxHealth;
[HideInInspector] public int displayHealth;
[HideInInspector] public int maxDisplayHealth;
public float sanity;
public float sanityThreshold;
[HideInInspector] public int displaySanity;
[HideInInspector] public int maxDisplaySanity;
public EntityType entityType;
}```
nvm
why UI mask doesn't work?
my maskablegraphic not getting masked
unity version 2021.3
my custom physics shape is not being used
,and i have a tilemap 2D collider. Instead of using my custom physics shape unity is counting an entire grid as a collider? any ways of fixing this?
nvm I'm just stupid
how do i make an object make a sound when the player collides with it in unity 3D
Don't cross post.
sry
Sound is played through a AudioSource component, so if your object has one (or you have a reference to one), you can call .Play from the collision event, theres many other properties like setting the AudioClip as well: https://docs.unity3d.com/ScriptReference/AudioSource.html - how the sound is heard, is determined by a AudioListener, there can only be 1 in the scene and by default its attached to the "Main Camera", and the Audio Source Spatial Blend and volume settings greatly affect where and how the audio source is heard, relative to the listener (assuming that the Game view audio isnt muted)
ok thanks!
my custom physics shape is not being used
,and i have a tilemap 2D collider. Instead of using my custom physics shape unity is counting an entire grid as a collider? any ways of fixing this?
any possible fixes, not links to things online since i searched everything
Hello, I got a question. for unity, anyone knows a tutorial where it teaches how to check the performance benchmarks? Bec for school I am doing a study between two algorithms and am comparing the frame time, load time, memory usage, cpu usage, gpu usage, input latency etc...
profiler
ty
show your tile asset properties
how do i make it so that i can record what button player clicked?
like i want to make custom keybinds but instead of having a super long scroll menu i'd like to listen to what the player clicks
What's the best way to calculate distance between objects if I don't actually need the distance, just to check which is bigger. I believe there was a function that doesnt calculate the square root
Yep (b - a).sqrMagnitude
Thanks
also, is this a proper way to remove list elements while looping through it ? for(int i = 0;i< chars.Count; i++) { if (chars[i].IsDied) { chars.Remove(chars[i]); i--; continue; }
I feel like this shouldn't skip any other elements if the current one is removed
Might be with that decrement, but to be safe I would do a reverse for loop myself
Most IDEs have a snippet for that, forr then tab twice
yeah, reverse sounds safer
Or if it's a List, then you can use .RemoveAll(c => c.HasDied) to do it in one line
Anyone having trouble uploading apps to Apple for distribution today (Xcode)?!
And faster, because it doesn't need to shift the whole list by one with each remove
i think your data is unordered, you can simply do this
for(i=0;i<Count;){
if(a[i] needed to be removed)->remove as swap back (ie swap it with a[Count-1]), Count--
else i++;
here the i pointer only increment when it meets a non dirty element
Why would some scripts in my project be able to access the Lean namespace while others aren't ? If that helps, the script that doesn't have access to the namespace is part of an asset(https://www.because-why-not.com/webrtc/)
Are you using assembly definitions? You may need to add a reference to another asmdef to be able to reference the namespace.
If not, do these errors appear in the Unity console, or just in VS? In that case, VS didn't pick up the changes made to the project, you need to regenerate the project files from Unity
They appear in the Unity Console. I tried the regeneration, will look the asmdef solution you propose !
Assembly definitions are files, you can easily check if you have some, by searching for any file with the asmdef extension
You can search t:AssemblyDefinitionAsset
problem solved. @simple egret @quartz folio Learnt something new ! Thanks, you are awesome.
foreach (KeyCode kcode in Enum.GetValues(typeof(KeyCode)))
{
if (Input.GetKey(kcode))
{
Debug.Log(kcode);
}
}
i'd like to store only the value before the last one how do i do that
Unclear what you mean
this records what button gets pressed but it gives about 40 outputs
and like it's
Joystick1Button9
JoystickButton9
Joystick1Button9
JoystickButton9 --> i'd like to store only this value in a keycode variable
Joystick1Button9
yes, it will debug every frame the key is held down
yeah and i don't want that
cuz when i use the gamepad it debugs Joystick1 then Joystick and i only want to store Joystick, which is the penultimate
so cache the kcode and check current against previous
i tried but I'm not able to do that. could u help me please?
Just use GetKeyDown instead of GetKey
there is that. and use break when the first one is hit maybe
but
KeyCode prevCode`;
then
prevCode = kcode;
in the if will cache the value
i did, but still that stores 2 value. one is Joystick1 and one is Joystick
could you show whole code pls
Two values are normal, the first indicates any joystick button was pressed down, the second one is that it comes from joystick 1. If you had a second one, it would have said joystick 2
so in fact a break; after the debug should do it?
i still have no idea what he is trying to achieve
Depends on if they want to know what button on which joystick was pressed, or just that a joystick button was pressed
Button remapping UI, if I read the question correctly
KeyCode lastCode;
foreach (KeyCode kcode in Enum.GetValues(typeof(KeyCode)))
{
if (Input.GetKey(kcode))
{
lastCode = kcode;
Debug.Log(kcode);
break;
}
}
lastCode now contains the keycode found;
I guess?
one second
Trying to make a payment on payments.unity.com fails saying ILLEGAL_TRANSACTION
My dashboard has been locked out
What could be the issue?
couldn't find the appropriate channel 😛
this one seems to be the most active one, lmao
could you maybe point me to the right channel?
tbh the forums or the new unity discussions would probably get better results
@knotty sun alright ty
hey. need some help with my camera. why does it flip upside down sometimes? i'm using eulerAngles to change the rotation
https://www.twitch.tv/videos/1851869007
when i use that function i showed above, the debug says:
Joystick1Button9
JoystickButton9
Joystick1Button9
JoystickButton9
and so on. I'd just like to save JoystickButtob9
Hi all, I have a somewhat unique question regarding the unity line rendering system. I'm trying to create a mechanic where the player can draw certain shapes with an outline of their movement, and the outline is constantly being checked for resemblance to these shapes. The line is stored in the script as a LineRender object. However, I have no idea how to go about this. I feel pretty competent in my math ability, so if there is some algorithms/mathematical concepts for checking the resemblance of a line represented by an array of 2d positions to an equation then that would be great, or some other unity recognician function idk. Any help would be appreciated, I'll also send a screenshot of what the line looks like if that helps
something like: https://math.stackexchange.com/questions/2731477/how-can-i-define-closeness-of-these-geometric-shapes
Given points on a 2D plane, what kind of metrics can be used to define if they closely fit either:
triangle
square or rectangle
circle
oval (circular but not oval)
(Image credit: StyleCraze.co...
yeah this looks like a great starting point, thanks!
i tried googling unity specific stuff because I didnt know how to word the problem for mathematics, and couldnt really find anything relevant
anyways this is a huge help, thanks again
no problem. i guess start with the basics/theory and then work up to unity specific things
Are enumerable methods like List.Any() expensive to be running frequently?
I'm trying to avoid duplicates on a list by checking something like if(!actorList.Any(a => a == actor)) but i'm not sure if there's a more efficient way, or if it's even worth worrying about duplicates that much.
Idk, you could use Contains instead
if you never want duplicates then a hash set could be faster than a list
***** ContainsExistsAnyVeryShortRange *****
*******************************************
List/Contains: 1067 ticks
List/Exists: 2884 ticks
List/Any: 10520 ticks
Array/Contains: 1880 ticks
Array/Exists: 5526 ticks
Array/IndexOf: 601 ticks
Array/Any: 13295 ticks
HashSet/Contains: 6629 ticks
***************************************
***** ContainsExistsAnyShortRange *****
***************************************
List/Contains: 4ms
List/Exists: 28ms
List/Any: 138ms
Array/Contains: 6ms
Array/Exists: 34ms
Array/IndexOf: 3ms
Array/Any: 96ms
HashSet/Contains: 0ms
***************************************
********* ContainsExistsAny ***********
***************************************
List/Contains: 11504ms
List/Exists: 57084ms
List/Any: 257659ms
Array/Contains: 11643ms
Array/Exists: 52477ms
Array/IndexOf: 11741ms
Array/Any: 194184ms
HashSet/Contains: 3ms```
😅
oh silly aia, ik all the server you are in
Just what I needed, bless 🙏
np
Do someone know how to compare objects colliders from a another object, So in my case i have the script attached to the camera and in the camera script i want to check if the grenade collider is colliding with the enemy colliders, I would be so happy if someone could answer my question, Thanks!🖐️
is the camera going to be the only object which cares about this collision?
if so, use an event
The camera have the script that will compare the grenade and the enemies colliders
I can't find a soulotion to compare collisons from another object
a better way to handle this is to have the enemies destroy themselves in their own script as opposed to using the camera's. You would do this by defining OnTriggerEnter in the enemy script as shown in the api docs https://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html
But if you need to have the camera handle this for whatever reason, then trigger an event in the ontriggerenter in the enemy script and have the camera subscribe to that event
this is a long article but it pretty much covers all the basics of creating events in unity if you don't know how to get started with them https://gamedevbeginner.com/events-and-delegates-in-unity/
WORKED, THANKS!
How would I give an ai the ability harvest crops like wild hemp plants and apples on trees
break it down to smaller mechanics you implement
Hi, whats the variable/parameter type that BoxCollider uses for you to select (in editor) a certain area?
Something like Vec3[] or Area?
Tbh my idea was having colliders for the plants and for the ai. If the ai were to sense it while wandering it would go and harvest it.
Basically if the colliders were to collide with each other it would sense it
Then it would harvest the plant when its close enough to harvest
hmm you can just use distance checks as well
Not what boxcollider uses but maybe you want a Bounds
yes, it's a Bounds
How do I make two objects the exact size? Working with relative size is kinda weird isnt it, if I have two objects I wanna make them absolutely the same size, how? In inspector if possible..
Need help with making the enemy ai use the same bullet controller the player is using
make them the same size in the modeling program, then.
it's all "relative size" because...how could it be anything else?
if I export a correctly-scaled brick and a correctly-scaled house from Blender, i'd expect them to not be the same size in unity
let me rephrase things here
what are you trying to do?
what part of your game are you creating?
not the sprite, the actual tile asset where you set which collider gets used https://docs.unity3d.com/Manual/Tilemap-TileAsset.html
Has anybody had an issue where the layermask for raycasts is shift in a direction? For me, it seems as though the collision box for raycast does not line up with my geometry and is shifted to the left
the "layer mask" is just a bitmask controlling which layers can be hit
so you mean teh actually collider doesn't line up
ok Why wouldn't it? The collision works fine for player movement
it also does log the 1st msg
aren't you simulating this stuff in a separate physics scene?
Perhaps, It is using getphysicsscene2d from a library I'm using, perhaps that could be causing it?
Apparently it is a security for multiple physics scenes in Fusion. I'm trying it with physics2d.raycast
So I need to make a programatical grid to store my cells (Each cell will be assigned enum/int)
I know I gotta make a loop inside a loop but I dont know how to make the actual cell grid
I would need something like this:
000100
010000
010010
0 is an empty cell
1 is a filled cell
Any have any tips?
2d array
to optimize the memory usage, you can consider allocate your 2d array with suitable primitive type
Same issue using just physics2d
oh wait
the ray you're drawing is 1 meter long
the raycast is 10 meters long
no wonder it's mismatched looking
the fourth argument of DrawRay is the lifetime of the line
the lifetime is how long the line stays on the screen
it has nothing to do with the length of the line
the raycast is completely correct. your visualization of the raycast is wrong.
Like you only get the "Waiting 0.1s" Debug.Log()? It's worth a mention that the latter WaitForSeconds() will be affected by timescale, and also that the coroutine will stop if the object which called StartCoroutine() is disabled/destroyed
I know, i am using Realtimeseconds because i wanted to test it.
however i fixed it, by instead invoking a regular void inside the same class as the coroutine. so someone'll have to make a bugreport that invoking coroutines from different classes is problematic
so someone'll have to make a bugreport that invoking coroutines from different classes is problematic
I don't understand the particulars - but I believe that that's the intended behavior. It would be nice if the docs would emphasize that a little more, however
forget everything i said.
the gameobject destroys itself after invoking the coroutine
well, now it says m_displayhit(). but that`s where it invoked the coroutine before.
so you were right!
it stops because the gameobject deletes itself
ahh gotchya 👌
Yeah that's a fun caveat to suss out 😅
i thought the Destroying = stopping coroutine only applied to the gameobject the coroutine is on
it does
i noticed xD
anyways, thanks for clearing things to me!
now i know too
Yes.
Think I got it thanks for the help
not the sprite or the tile map, the tile asset. See the link
Has anyone ever experienced noise on mobile builds? It's a 3D heavy game and when switching a certain scene it does this...
Hello, this is a very specific situation, but I'm trying to network my hololens with my computer using ZeroMQ but it just crashes unity when I deploy it. Has anyone tried to do this before?
maybe ask in #📱┃mobile
hello, does anyone know what is the best "how to make an online game" turtorial? or just a really good one
Camera.current is null inside OnBecameInvisible. Is this a bug or by design?
don't crosspost. i don't think this question has a meaningful answer.
i just wanted to know if anyone has some suggestions
Hi there, I have a issue with loading serilized data from json (database). My JSON string has a lot of characters and there are some incorrect data when loading it because the objects are in the wrong positions e.g. Is it possible that JSONUtility can't handle that much data which is causing the corruption? When using wrapper it counts around 80k characters with spaces. Anyone had similar problem or have diffrent solution for that. It is my first time having to do anything with serialization
. Sorry if I'm talking nonsense but it's hard for me to explain.
The method is not called per camera render, but per frame. A renderer is considered invisible only if no camera can see it for that frame, including the scene view camera.
i doubt that it gets "corrupted" when you have too much text
so Camera.current is availalbe for what methods?
anyway it makes sense what you say now that I think of it
Use this function only when implementing one of the following events: MonoBehaviour.OnRenderImage, MonoBehaviour.OnPreRender, MonoBehaviour.OnPostRender.
Maybe not corrupted but some of the object are not getting loaded at all or they lack any hierarchy relations where after looking at JSON file looks fine
.
perhaps your code is wrong
also, this is only relevant for the core RP, iirc
try to stay away from multiplayer until you built a good grounding / experience
thanks!
{
if(addedwin == false)
{
if(win.Value != -1)
{
addedwin = true;
wins[win.Value - 1] = wins[win.Value - 1] + 1;
}
}
}``` how come when this method runs, any other value that isnt wins[win.value - 1] gets set equal to zero
there is no instance where wins[i] gets set to null, they are instantiated with a value of 10
you'd have to show the rest of your code, including how and where this function is called
how?
show the rest of the code
{
addWins();
GameObject.FindGameObjectWithTag("UI").GetComponent<NetworkUI>().win(playernum.Value);
}``` method is called here. win.value gets set to a value when a player collides with the goal
{
wins = new int[] { 10, 10, 10, 0 };```
array created in start
not created, assigned a value
private int[] wins;
created in the class not a method
Show the full script please
in a paste site ideally
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
if(collision.gameObject.tag == "Finish")
{
win.Value = (int)(playernum.Value);
}```
What's stopping this from running on every client and thus all of them trying to change win.Value at once?
it only appears to run on the colliding player, that wouldnt cause this issue would it?
maybe ill stick an isowner in there
Yes it runs on the colliding player but on every client, right?
its not supposed to
its supposed to set the win value to the assigned number of the player that won
every client will try to do the same thing though - I guess it's confusing that each player object has a variable on it that is saying which player won
this class seems to be doing way too much overall
true
it seems to be both a character controller and some kind of scorekeeper system
i was never taught how to code, all my games end up having everything in the movement class
and a UI updater 🤔
it's an easy thing to do
im almost done with the online part of my game tho so i wont have to touch it much
anyway what makes you say this all gets set to 0?
How are you determining that?
{
pla = GameObject.FindGameObjectsWithTag("Player");
winText.text = "Player " + (playernum) + " Wins!";
playerwintext[playernum - 1].text = "Player " + playernum + ": " + pla[playernum - 1].GetComponent<glide>().getwinsmethod(playernum - 1);
scoreVisibility(true);
StartCoroutine(waitfornextscene());
}``` win method, the score for every other player gets set to " "
Ok so... to get this straight... each player object is storing an array which keeps track of all player wins. And then to display the score you go to each player and fetch ONLY THAT player's win from that player's glider component
why not just have a single int winCount variable on each object that tracks the wins for that particular player
since you're only reading the wins for that player from it anyway
I don't see the point of the array
also where does this code live and get called from?
hold up
i think that its null because the scene gets reloaded, along with the scoreboard
that was my initial idea but the client couldnt read the hosts variables
the fix to that is to fix that lol
not to make each client track the scores independently
I'm not really exactly sure what your problem is but it's related to that whole setup
https://medal.tv/games/requested/clips/1eNHMUeJEcuQI4/d1337XRkawIY?invite=cr-MSxKTnYsMjYzNjQxOTcs
Hello,
I am attempting to make a restaurant game and the npcs coming in are supposed to sit down (animation) after their transform being set to a gameobject's transform
For some reason there is always an offset on the y - Axis, I am not sure why
I am also unable to move the object's Y axis in runtime
Components:
Rigidbody
2x Colliders (one with, one without trigger)
Navmesh Agent
Script
Animator in the child object
private void OnTriggerEnter(Collider other)
{
if (other.name == "WalkToPos")
{
nav.ResetPath();
animator.SetBool("isWalking", false);
nav.updateRotation = false;
Rigidbody rigidbody = GetComponent<Rigidbody>();
rigidbody.velocity = Vector3.zero;
rigidbody.constraints = RigidbodyConstraints.FreezeAll;
StartCoroutine(CustomerSit(other.transform.parent.Find("SitPos").gameObject));
}
}
IEnumerator CustomerSit(GameObject sitPos)
{
yield return new WaitForSeconds(0.4f);
transform.position = sitPos.transform.position;
print(transform.position + " " + sitPos.transform.position);
print(transform.position);
transform.localRotation = Quaternion.Euler(0, 0, 0);
transform.rotation = Quaternion.Euler(0, 0, 0);
Animation customerSitAnim = GetComponentInChildren<Animation>();
animator.SetBool("isOrdering", true);
ChooseRandomItem();
sitting = true;
}```
Watch Bug Help 18/6/23 and millions of other Requested videos on Medal, the largest Game Clip Platform.
you're setting the local rotation to zero, then the rotation to zero
neither of these care about the rotation of the seat
seems weird
as for the incorrect y position, i guess you just need to add an offset?
the origin of the model may not be the right place to put them
transform.localRotation = Quaternion.Euler(0, 0, 0);
transform.rotation = Quaternion.Euler(0, 0, 0);``` yeah this second line completely invalidates/overwrites the first line
setting localRotation to zero would make sense if it was parented
at least, more sense
you are mixing physics and manual movement/rotation. Try turning the Rigidbody off
Ah yea true, at some point I also had problems with rotation so I was desperate haha, will remove that though
I honestly don't think that's the issue, the model gets put to the right position but then for some reason moves itsself down for some reason
I have / had a print function which prints the location before and after the position was set and the position which was printed would've been right but when i go into the inspector it automatically changes
i see zero frames where it's not stuck in the seat
One second, let me show you, it isn't visible
sounds like the animator is moving it, then
although, i'm not sure where this script is
Also happens if I disable them, though it
shouldn't be able to change it since the animator is in the child object
^Didn't screenshot but it's the exact same position as before
Maybe you're intending to set the character's localPosition to sitPos instead?
All the tile assets are set to sprite
No, even though there is a parent object which stores all the prefabs its position is set to 0
If anyone has time and would like to help me fix this, I'd be really greatful if I could show them the game via discord stream, I am extremely confused on what's causing the issue
The reason I was asking was that the positions displayed in the console log vs the inspector here could well be the same world position, as the one from the inspector is local position. But which object is that inspector ss from/what object is the posted code attached to?
I see it's this one:
ah alright 👍 :/
Tbh I feel like it's one of those problems where it's a really simple solution but like I don't understand what the cause for the "offset" is, I believe I've checked everything
If there is no position that is offset, than I believe the animation has the issue.
If there is an animation*
I cannot figure out why i'm getting a NullReferenceException: Object reference not set to an instance of an object error when running the following code. everything is assigned correctly and I don't know whats going on.
[SerializeField] private Toggle speedrunToggle;
[SerializeField] private Toggle developerCommentaryToggle;
private void Start()
{
if(PlayerPrefs.GetInt("speedrunToggleSwitch", 0) == 0)
{
speedrunToggle.isOn = false;
} else {
speedrunToggle.isOn = true; <--- THIS IS THE LINE THAT IS TRIGGERING THE ERROR
}
if(PlayerPrefs.GetInt("developerCommentarySwitch", 0) == 0)
{
speedrunToggle.isOn = false;
} else {
speedrunToggle.isOn = true;
}
}
speedrunToggle is null / unassigned
like in the inspector?
note that you might have more than one copy of the script in your scene.
yes in the inspector
I have already tried disabling them, either way the animator is in the child object so it wouldn't have an effect on the paren't transform
this is whats so confusing to me
is there a way to check if a script is attached twice?
this
you can search the scene for copies of the script
You have another instance of this script attached somewhere else, check for t: GameplayTab in the Hierachy
in the hierarchy window type t: GameplayTab
okay thank you! ive never used the search before
oop foun dit
thank you so much @leaden ice and @simple egret
There is either an offset of position or an animation that offset it. Nothing I can do from here, you need to investigate by yourself. There is no magic.
this should be it?
Yeah... I think this one's probably out of my wheelhouse - especially if it has something to do with the animator. I've only really got random stabs in the dark to try and understand what's going on here, more than any really plausible angles.
I think it may be worth throwing a print(transform.localPosition); in with the others just to be absolutely sure that it's moving afterwards as you suspect it is...
I can't quite make sense of how in the video C_Table1_1's center pivot is 5.4 units below CustomerPrefabs, but in your inspector screenshot (which is presumably with the real pivot) the position is 1.2 units above CustomerPrefabs - unless C_Table1_1's pivot point is 6.6 units above it's center?
Hey, still trying to figure out how to call and assign a debuff. I'm getting close but still missing some core components. Would you compare two enums, and if so how? Seems like that doesn't work since it can't equate them. I'm trying to push values from the onTrigger into the player debuff, and that pushes values into the UI. Alotta back and forth and trying to figure out who stores what and who stores the enums and how to read those values to switch things like text/sprites to update the UI
Here's the
PlayerDebuffManagerplayers script, it uses a dictionary to store active VFX so debuffs can't stack if already existing: https://pastebin.com/vnWQ6Z2u
Here's theDamageVolumeConditionalscript which triggers the debuff using an onTrigger (trap, enemy, etc) https://pastebin.com/grRQxHHB
Here's theDebuffPrefabUIprefab that spawns in the UI. https://pastebin.com/bd3HaDN2
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Also need to have a setup where if a condition already exists, it's either cleared or renewed so it's reapplied without instantiating another cached UI object. (to avoid visual stacking). System seems to be partially working. It is only spawning 1 prefab and it does show the tick counting down/deleting. Just unable to pull data and assign different values from a scriptableObject (not sure how, i'm assuming an enum switch to assign scriptable data?)
no. At some point you created tile assets. Go set the collider type on those assets
https://docs.unity3d.com/Manual/Tilemap-CreatingTiles.html
https://docs.unity3d.com/Manual/Tilemap-TileAsset.html
i set all the assets colliders to sprite
for the tiles
that is 1 wall
and every tile asset has the same settings
- Don't think it can have anything to do with the animator, animations only affect the child objects of "C_Table1_1"
- screenshot local position = world position
- Sorry a litte confused 😅, where are you getting the pivot numbers from?
Ah shucks. I was really hoping for that local log 🥲
- From the original video, where the tool Pivot Mode was set to "Center." It's probably not relevant - it just struck me as weird that the scene grid could be seen outside of the window which is presumably at
y=0, yet whileC_Table1_1's center appeared to be well above that plane within the scene (judging by the transform gizmo), the inspector listed it'syposition at-5.4
oh i see, yea the parent object had the y axis set to -5.4 before, i changed it to 0 but didn't have any effect since i only worked with the global position
Ahh gotchya 👌. That makes my brain feel better anyway
Hahaha
Any chance I can stream you it? maybe it's some obvious issue, because i am completely confused
not planning to talk in vc tho
I'm really fairly new to Unity and reckon I have much less to offer than anyone here - but I could do that in a few hours
Ah I see, no worries, well if you want you can still take a look, maybe it's a simple thing I am just not seeing
Gameobjects serialization problem
why is this false?
Debug.LogAssertion(tilemaps[0].id == TilemapID.BASE); // .id is a TilemapID who's id is "base"
``````cs
[System.Serializable]
public sealed class TilemapID
{
public static readonly string[] ID_LIST = new string[] { "base", "foreground", "background" };
public static TilemapID BASE { get => new(ID_LIST[0]); }
public static TilemapID OVER { get => new(ID_LIST[1]); }
public static TilemapID BACK { get => new(ID_LIST[2]); }
public string id;
private TilemapID(string id)
{
this.id = id;
}
public override string ToString()
{
return id;
}
public override int GetHashCode()
{
return id.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj is TilemapID id)
return this.id.Equals(id.id);
else
return this.id.Equals(obj);
}
public static explicit operator string(TilemapID id) => id.id;
public static explicit operator TilemapID(string s)
{
for (int i = 0; i < ID_LIST.Length; i++)
{
if (ID_LIST[i].Equals(s))
return new TilemapID(ID_LIST[i]);
}
return null;
}
}
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
what?
Ah I see no worries well if you want you
[Android] Hey guys, how to detect if the player clicked on the go back button? Or "slided back" in the new android full screen immersive mode?
Why is what false?
the first line seperated from the rest, sorry:
Debug.LogAssertion(tilemaps[0].id == TilemapID.BASE); // .id is a TilemapID who's id is "base"
Because classes use reference equality by default and you haven't defined a custom .Equals implementation that would change that
I did
public override int GetHashCode()
{
return id.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj is TilemapID id)
return this.id.Equals(id.id);
else
return this.id.Equals(obj);
}
did I not do what I think I did?
You didn't override the == operator
Hello there, when doing inheritance, is there a way to hide or show fields on the inherted classes (on the inspector)?
Lets say I have an int on the base class, and I don't want it to be visible on all the classes that derive from it, rather I want to show it on specific classes
you can use [HideInInspector] if you have it showing but dont want it
On my base class I am doing this
[HideInInspector]
public CombatStances targetStance = CombatStances.Stance1;
and on the class deriving from that, I am doing this, but I can't view the field on the inspector
[SerializeField]
public new CombatStances targetStance
{
get { return this.targetStance; }
set { base.targetStance = value; }
}
How can I do that on inherited stuff?
oh i misunderstood what you wanted visible
No worries
I just want some classes to have that specific variable shown on the inspector
first off - Unity doesn't serialize properties, ever.
second, if you want to change how the script is rendered in the inspector, you'd need to write a custom inspector
Ah, makes sense, so there is no way other to making a custom inspector if I want a field to be visible on specific classes?
cant it serialize if its using auto-implemented properties?
yes, but that is not the case here
Yea was just wondering because they said "ever" which i assume meant every case
not sure about this
get { return this.targetStance; }
set { base.targetStance = value; }
shouldn't they both be base.
@swift falcon why u X react? it does work
Hi all. Maybe somebody can help me. I tried since a long time now to solve this problem, but all the solutions are not really statisfying.
I am programming a 3d game and when I jump at walls and trees and everything that stands upright, my character gets stuck on the side of it.
I tried all these things:
- raycast forward and backward and stop movement and add a force down - this seems not really working for all situations, as the raycast is not seeing everything and backward raycasting does not seem to work either
- adding material with zero friction to all the walls and trees and the player - this works, but is it really the idea to set the zero friction material to everything vertical ?
- Sweepcast is somehow not good as it is casting the floor and low object too....
Has anybody here a good solution for that? I hope I found the right channel for my problem 
you dont assign the friction to everything vertical, just your player. But if you really need the player to have friction, then you can try to not allow movement towards the object while against it. The player should be able to slide down it then
adding a force down wont do anything, gravity is already doing this (assuming you are using rigidbodies) but the friction and character constantly moving towards the object is stopping it, you would need a force backwards which might be hacky. Id still just do 0 friction
I have problem with cameras, I want to add card system on top of my 3d game, and I've setup overlay camera to handle card system. And if something is closer to game camera than cards are to overlay camera then it is still on top of my cards. How to handle that overlay camera is always on top no matter what?
What do you get?
Thanks a lot 🙂
[field : SerializeField] public int Property { get; private set; }
No, I meant how does it look in the editor? My bad, this is the first time I am hearing about this.
Let me try this out.
it looks normal
with one interesting caveat
[field : SerializeField] public int property { get; private set; }
this will show up lowercase in the inspector
very weird looking
Test code:
[SerializeField]
private int Auto { get; set; }
Rider:
you forgot [field : at the start
Sorry, I want to ask questions about the topdownengine package. Which channel should I go to?
sorry to bother you
trying this
that makes the attribute target the backing field
otherwise, it targets the property, which is not useful
I think I know this syntax for naming the attributes explicitly for the language token -- I've seen it used for assemblies.
Okay so for now it doesn't serialise default values.
[field: SerializeField]
private int AutoPotto { get; set; } = 69;
no, it serialized the 0
Should the zerofriction on the players collider be sufficient? When I do that I still get stuck on the wall. If I add the zerofriction on the wall collider too, then it works.
adding a field initializer doesn't do anything to the already-serialized value of 0
resetting the component or adding a new one will make the field initializer's value show up
yes it should be, but you should select Friction combine: minimum then
ah o.k.
Yeah, they should, I was just testing random stuff to check if it worked
It works... omg and I tried so many things. Thank you so much 🥰
No. It can serialize the backing field of an auto property, if you ask it to. It will never serialize a property.
ah i see what u mean
Why is System.Text.Json.JsonSerializer an internal class here?
Newtonsoft doesn't support ReadOnlySpan unfortunately.
I'm trying to achieve this:
var response = System.Text.Json.JsonSerializer.Deserialize<ResponseObject>(
downloadHandler.nativeData.AsReadOnlySpan()
);
Broader scope.
What/How do you mean?
What are you doing ?
Oh, I get it. You’re trying to deserialize the result of a download
I thought you were trying to serialize something with a ReadOnlySpan in it
You should be able to get a string out of that span. Would have to look closer
at dinner rn
I don't want a string from a span if I can help it!
I'm trying to use this class but it's marked as internal for some reason. Not sure.
The documentation states it is also available as a NuGet package, which would mean I could potentially get its DLL somewhere if needed.
Hello! Hope you are having a great night! I am having some struggles with deciding what architecture to use for my next Unity Project... Basically, I have been doing projects for fun for a while but now it's gotten kinda professional... so I wanted to take it serious!
I have been looking at MVC, but then read that it's not that great... I have tried to learn about architecture for a while but it all seems really project-specific which kinda makes sense
So my question is, how I can know if I'm doing things properly? Should I use MVC (Model View Controller)? Or go for another route? What's your experience?
A lot of it is project-specific
Also something I am learning to judge only now: use the profiler to guide your architectural decisions.
I see... Honestly, I'm kinda nervous because I'm the one in charge of that and I don't want to make people have problems because of me
So I have been struggling to get it right
But yeah, there are no clues to that
No way to have the cake and eat it too.
Mhhh
one thing I've gotten into the habit of: the player is not special
everyone is an Entity with a Brain that tells it what to do
Don't focus on the humans you have no control over, focus on the performance which you do have control over.
Then write things which don't make your eyes hurt.
I understand, yeah
i've gone through several games and, generally speaking, each one is better-structured than the last
doing game jams is a good way to QUICKLY gain experience there
I made a soulslike last last year and I took the opportunity to learn how to use state machines properly
(using the Animancer package, specifically)
I have done some kinda advanced projects for a while now but I wanted to start using some more professional techinques
Making somewhat-accurate aircraft movement does involve scouring the source code of physics engines underneath the hood, for example.
I don't want to think of doing that right now hahahah
But hey, thanks for the quick talk, kinda got overwhelmed in there for a bit and needed to chat
Go do those game jams, I didn't so I generally suck :P
I like to think that I'm getting "more professional" as my games make me less and less upset with my past self
that's a nice way to put it
Noted :P
So I found this script for moving platforms using a character controller
it works pretty well but it has one problem
You continue to move on the platform until you fall on something else
For example if I jump, i still move with the platform
How do I make it so that it if Im not on it, i wont follow it?
you'd need to set activePlatform to null the moment you aren't touching a platform
I tried this and it doesnt work if(hit == null) { activePlatform = null; }
I imagine KCC or other kinematic movement logic allows tons of optimisations if one doesn't target physics.
it's a little harder to set up than the default character controller, for sure
i like it
well, yeah, you don't get a message when you don't hit something
try using the collision messages like OnCollisionStay or Exit
What you are looking for is a hit with a result that is not a platform. Or the Unity Message callbacks!
i'm not sure if you'll get those from the character controller
if you're airborne, you will hit nothing
maybe you can just clear the active platform every frame. i'd have to stare at the script harder to figure out if that works
Ah, I thought we had a longer ray.
the character controller page says it has collision messages.. i think
https://docs.unity3d.com/ScriptReference/CharacterController.html
the OnControllerColliderHit happens while performing a move
it just inherits from collider so it should work
ah, right
depending on the gameplay possible, might need to store what platforms are currently in contact then only make it null if none are in contact
like if 2 sliding platforms are next to each other, making it null might just make you stay still
tried collison exit doesnt work
actually to hell with this script
Why do guides keep gaslighting me?
they arent, and thats not at all what gaslighting means lol
if you dont understand whats happening in the guide, you wont be able to edit it
well it feels like it, cause everytime i use one its got something wrong in someway
Welp I'm still here if anyone wants to know
because movement is very unique to your game, most arent tuned to exactly how you want it. They're built for the purpose of the demonstration. Even most video tutorial movement guides are massively flawed in some way and dont allow for easy customization
looks like your picking up the class from the wrong dll
public class CustomLight
{
}
public class CustomPointLight : CustomLight
{
public float radius;
}
List<CustomLight> lights = new List<CustomLight>();
// in a for loop
CustomLight currentLight = lights[i];
//cant get this because the class can be anything, how can i tell my compiler that it is %100 a point light?
currentLight.radius
how can i get that radius property if i am sure it is a point light? how can i tell my compiler?
Yeah, something didn't feel right about that. Why is it internal in that DLL?
No idea, but looking at the docs System.Text.Json namespace is .Net 7 so wont work with Unity anyway
Not according to this
https://learn.microsoft.com/en-us/dotnet/api/system.text.json?view=net-7.0&viewFallbackFrom=netstandard-2.0
Provides high-performance, low-allocating, and standards-compliant capabilities to process JavaScript Object Notation (JSON), which includes serializing objects to JSON text and deserializing JSON text to objects, with UTF-8 support built-in. It also provides types to read and write JSON text encoded as UTF-8, and to create an in-memory document...
That's a nuget package so will have to be installed manually
certainly got nothing to do with ReportGeneratorMerged dll which is what you are using
Hey, I'm still trying to figure out how to push/extract values from classes to create a debuff system. i've got two enums that im trying to equate in order to use a enum switch for each (but they can't be compared since they are considered two diff enums not one). The values are then pushed into a UI prefab which spawns the debuff icon + timer to notify when it'll wear off.
Would you use some kind of return value in the switch enum? and how would that be done if so? Also trying to incorporate a scriptable object, but unsure how and if that'd be an array, or per variable (i.e. "burningDamage = debuffSO.damage"; "iceDamage = debuffSO.damage";)
well the easy way to compare enums is to cast them to int
Gotcha, does my setup look correct for what I'm trying to do? Unless there's a better method than comparing two enums
I do not look at screenshots of code
Ok I can pastebin all 3
it is also 2am so I aint gonna examine your code either
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
O gotcha fair enough
if i do nodes.Remove(node) and node does not exist in the list do it get an error ?
No - it'll just return false
ok thanks
I have this issue where my z axis movement isn't working but my x axis movement is?
how do i make the inspector display this
public List<List<ConnectionsV2.References>> connectedNodes = new List<List<ConnectionsV2.References>>();
be more clear this is not enoght for you to get help, proved how is not working and the code
if (rigBod.velocity.x != 0 || rigBod.velocity.z != 0 && Input.GetKey("left shift"))
{
hMulti = 6.2f;
zMulti = 6.2f;
} else hMulti = 3.2f; zMulti = 3.2f;
//Move Input to Horizontal string
Move = Input.GetAxis("Horizontal") * hMulti;
Depth = Input.GetAxis("Vertical") * zMulti;
}
//Fixed Update method
private void FixedUpdate()
{
//Vertical movement velocity update
rigBod.velocity = new Vector3(Move, rigBod.velocity.y, Depth);```
unsure of how to format
hMulti and inputgetaxis horizontal work fine
you use the simbol ` 3 times at the start and end followed by csharp at the start
wait is your game 2d ? befcause the z axis is the 3d axis, you need to use y for up and down
Unity won't serialize a list of lists. One common work-around is to create a serializable class or struct, and add your nested list as a member of that instead.
No it's 3D, I'm trying a paper mario type
its a pill shaped collision box though despite being a quad with a sprite on it
else hMulti = 3.2f; zMulti = 3.2f; this means that else hMulti = 3.2f and always zMulti = 3.2f;
happy to help

any one knows ?
oh sorry
no problem 😅
didn't notice
{
hMulti = 6.2f;
zMulti = 6.2f;
} else
{
hMulti = 3.2f;
zMulti = 3.2f;
}```
Like this?
GOT IT the z axis was locked
so i just implemented DFS to my game and i wanted to see it working so I added the following code to see it working.
if (visualize)
{
node.originStructure.GetComponent<SpriteRenderer>().color = Color.blue;
DateTime startTime = DateTime.Now;
TimeSpan duration = TimeSpan.FromSeconds(1);
while (DateTime.Now - startTime < duration)
{
Thread.Sleep(10);
}
}
But it does not update the color of the gameobjects untill the end, some one knows how to solve ?
what are u trying to do with that code..
Do I have to do Async scene loads in a coroutine? Or if I don't care when it is done I can just call it and forget about it?
Looks like a nice way to freeze Unity for the duration
true but is just for debugging
still if you know a better method
It's not going to help you debug anything
No game time or frames will pass while you sleep the main thread
betwwen each eateration of DFS make it wait and color the structure blue so i see DFS working
You won't be able to see anything working
indeed as i said it does not work and freezes the game
Put your DFS in a coroutine and insert yields between iterations if you want this
Do not ever use Thread.sleep in Unity
but how do i make the DFS wait for the next iteration ?
void Initialize()
{
foreach(ConnectionsV2.References node in nodes)
{
if (notVisitedNodes.Contains(node))
{
visistedNodes = new List<ConnectionsV2.References>();
adjacentNodes = new List<ConnectionsV2.References>();
//after we reset everything we run DFS
DFS(node);
NodesNetworks nodesNetworks = new NodesNetworks();
nodesNetworks.network = visistedNodes;
connectedNodes.Add(nodesNetworks);
visistedNodes = new List<ConnectionsV2.References>();
}
}
}
``` here i wait for the function to finish before gointg to the next sets of nodes, how do i make this stack wait for DFS to finish ?
make the DFS itself a coroutine
as mentioned
this code is irrelevant
the DFS itself is what matters
if that stack does not wait for DFS to finish DFS will break thats the problem
I have no idea what this sentence means
if you want something to happen at the end of the DFS, call it at the end of the DFS
or have another coroutine run the DFS coroutine and yield on it
I dont know why but i feel like the DFS function isnt an entire DFS, unless u are actually running the algorithm many many times
wait i will send you the entire script or we just get confused
I would assume a function called DFS would be an entire DFS
either way though, u can just store the results of the DFS and have another coroutine run through that loop, highlighting it blue with a yield between each iteration
my guess is that you probably unfortunately wrote it recursively
this would make it so the visualization is separate from the algorithm
i followed a tutorial that said to do it recursively
is that bad ?
boo
XD
i wouldnt call it horrible, but theres no reason to use recursion in c# ever basically
why ?
its never more optimal in c#
it's less efficient than just using a Stack
and it will make it much much harder to do what you want
void DFS(ConnectionsV2.References node)
{
notVisitedNodes.Remove(node);
adjacentNodes.Remove(node);
visistedNodes.Add(node);
AdjecentsNodeAdder(node);
if (visualize)
{
node.originStructure.GetComponent<SpriteRenderer>().color = Color.blue;
}
if (adjacentNodes.Count != 0)
{
DFS(adjacentNodes[0]);
}
}
This is the code i wrote, i should i instead make a while loop that keeps looping untill all is done ?
well sure but you need either a Stack or a Queue to hold the fringe nodes
honestly i would separate the visualization from the DFS regardless
isn't a stack just a list ?
no
well you can make a stack efficiently with a list
but a stack specifically has Push and Pop functions which semantically work a certain way
regardless when you do it non recursively it is easy to add yields to it
e.g.
while (fringe.Count > 0) {
var current = fringe.Pop();
// process the thing
yield return new WaitForSeconds(time);
}```
much simpler than in the recursive approach
its been so long since ive used DFS, but that original code really doesnt look like recursive dfs to me
bump
true, but i just had a terrible idea, that is probably going to work but you are not going to like: call a function that colors the node after a while, that while is the order of the node * the time that i want to wait. Duck tape and glue 🧐
probably isn't but it does his job
what?
let me do it and i will show to you my terrible idea
there is no "after a while" with your code
when you call DFS the whole thing happens instantly
At that point, just do what i said. Let the DFS run, get the returned list, use a coroutine with yields and color it
that being said you could do the DFS instantly, and just walk the returned list slowly
yeah
yeah i will do that
thanks to the visualization i just noticed that i actually wrote bfs lol
hey, I have a bunch of procedurally generated meshes strung together all under one parent object. To spawn trees on them, my first thought was to choose random vertecies in each mesh and spawn trees on those. but my code doesnt work. does anyone know how to help? thanks.
using System.Collections;
using UnityEngine;
public class RandomTreeSpawner : MonoBehaviour
{
public GameObject treePrefab;
public Transform parentObject;
public int numTrees = 10;
void Start()
{
SpawnTreesOnRandomVertices();
}
void SpawnTreesOnRandomVertices()
{
MeshFilter[] meshFilters = parentObject.GetComponentsInChildren<MeshFilter>();
Debug.Log(meshFilters);
foreach (MeshFilter meshFilter in meshFilters)
{
Mesh mesh = meshFilter.mesh;
Vector3[] vertices = mesh.vertices;
int numVertices = vertices.Length;
for (int i = 0; i < numTrees; i++)
{
int randomVertexIndex = Random.Range(0, numVertices);
Vector3 randomVertex = vertices[randomVertexIndex];
Vector3 worldPosition = meshFilter.transform.TransformPoint(randomVertex);
Debug.Log(worldPosition);
GameObject tree = Instantiate(treePrefab, worldPosition, Quaternion.identity);
tree.transform.parent = meshFilter.transform;
}
}
}
}
there are no errors, but when the game is run, nothing happens
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
And:
nothing happens
Nothing? What about your log statements?
oh, im sorry
heres all i get from the log
you should print the length of the array
true
Debug.Log(meshFilters); is just going to print the type (hence your log showing an array)
but if that's all that prints my guess is the array length is 0
you said the stuff was procedurally generated, so maybe that generation hasn't happened yet by the time this code has run - hence the empty array
{
Debug.Log("MouseOver");
}``` why tf does this not work its a ui element and has a box collider
ohh that makes sense
yeah the array is empty
how can I delay the code just a little bit for the meshes to generate?
should i use WaitForSeconds() ?
You don't use this for ui
There's the event trigger component
simple answer could just be to do the mesh generation in Awake and this thing in Start
or call this code after calling the mesh generation code
okay thanks so much!
whats that lol
ohh
thats pretty nifty!
box collider + ui element is 🚫
you can also add IPointerEnterHandler to your script
yea that was my last ditch effort
@thorny onyx
yes that is the event trigger
i asked this earlier but no one answered, whats the best way to basically just render a 2d array of colors to the screen
i want to make a game similar to noita and im trying to render the elements to the screen
How do I use OnTriggerEnter2D(for 2D game) or other built in collision events with disabled collider?(I don't want collision to be affected by physics etc so I want to disable it, but keep the events triggering)
so I want to detect a collision, but not actually collide(not be blocked by a collider) i.e. allowing the player to walk through walls, but detect when player collides with the wall(or when player is inside a wall etc)
Just it being a trigger will make it not be affected by physics though @upper pilot
// strings s1 - s10 are 19 random numbers strung together (first being random from 0-8 so it doesn't go over the long limit)
string result = roomdata;
Regex.Replace(result, @"=1=|=2=|=3=|=4=|=5=|=6=|=7=|=8=|=9=|=10=", m =>
{
Debug.Log($"Match Value: {m.Value}\ns1 Value: {s1}\ns2 Value: {s2}");
return m.Value switch
{
"=1=" => s1,
"=2=" => s2,
"=3=" => s3,
"=4=" => s4,
"=5=" => s5,
"=6=" => s6,
"=7=" => s7,
"=8=" => s8,
"=9=" => s9,
"=10=" => s10,
_ => "",
};
});
Debug.Log($"result: {result}");
return result;
```Why is regex not replacing? The debug statement lists out the `m.Value`s correctly, but the result is the unmodified`roomdata` string. Even if it wasn't matching something in the switch statement, a match should still get replaced with "" right?
Because strings are immutable and you need to use the string returned by Replace
i just realized that, 😭
been running into too many easy problems today, time to take a break for a bit i suppose.
You take a break and the problems are doing pushups and getting stronger.
I will be learning unity for a school study to compare between two procedural map generation algorithms bec unity has alot of tutorials on procedural map + it has profiler which is important in order to compare. However I wanna learn Unity tools more than learning how to make a game bec I just need to understand these two algorithms and learn how to alter them to check different scenarios. For this reason I wanna focus on the tools of unity, anyone knows agreat free course/tutorial? on youtube
ello lads. i'm working on implementing sound effects into my project like footsteps, crouching, jumping, etc. my question is what might be an efficient way to go about doing that if i plan on including different sounds for the terrain? i reckon a switch statement would work, but is there a better method to doing this than putting a switch statement inside of each switch statement? it doesn't seem like it wouldn't work, but i'm just wondering if there is a better way
Hi, to be honest, I'm not sure if this will be relevant, but maybe skim through this and see if it might help?
https://www.youtube.com/watch?v=nqAHJmpWLBg
Check out the Course: https://bit.ly/3i7lLtH
Want cleaner code? Keep an eye out for code smells in your unity3d project and c# code.. We'll talk about why switch statements can indicate architectural issues in your code, how to tell if they're actually an issue, and some alternatives to make your unity project and code architecture ...
Vector2Int startPixel = new(Random.Range(0, mapdata.GetLength(0)), Random.Range(0, mapdata.GetLength(1)));
for (int x = startPixel.x-2; x <= startPixel.x+2; x++)
{
for (int y = startPixel.y-2; y <= startPixel.y+2; y++)
{
if (x < 0 || x > mapdata.GetLength(0) || y < 0 || y > mapdata.GetLength(1)) { continue; }
mapdata[x,y].Update(this,x,y);
}
}```
im getting index out of bounds errors, shouldnt the if statement avoid this?