#archived-code-general
1 messages Ā· Page 425 of 1
and fwiw, i just installed that version of the editor and created a project in it and i can see the newer versions of the packages mentioned
very weird
that is something you should absolutely learn about and use. version control software (like git or unity version control) can save your ass
you should always be using version control with your projects, especially if it is something you intend to work on for a while
which do you reccomend? i have use github before a small bit
alr ill redownload that then
i just made a repo for it, so i just push on the github dekstop whenever im done right?
with that do you mean unity 6 or 2022.3.58f1?
If you're not on unity 6 don't change to it. Patch update means the latest patch version change according to semver. I don't see why you couldn't update to latest minor version and patch version though.
alr
like Steve said, latest patch would be the last set of numbers at the end of the version number so 2022.3.58 would be the lastest patch for that version of the editor. unity 6 (or 6000.0) is a different major version
https://semver.org is a good reference @rocky heron
Hey, how do top down games usually do damage with melee types?
I've been trying multiple methods and each has a drawback. I'm looking to create Vrising style snappyness.
- Tried collider based, but apparently that's expensive especially if I want enemies to share the same system and especially if there are alot of them.
- Currently trying physicals overlap. requires a special setup, but apparently checking frame by frame is cheaper than using physics. The issue is that its dependent upon the animation as well.
- Considering decoupling animations from logic. Spawning a fake/invisible weapon that rotates flush to "sort of" match the weapon. Desync may occur, but it will always hit the target
- Considering a slash mesh with either a meshcollider, or multiple rotated/stacked physics overlaps fanned out to get a crescent shape.
issues with animation based colliders- timing is based on animation swing, and the accuracy of the angle. since im going for top down, i've already seen an issue where from the top a slash appears horizontal, but in fact is angled and it totally misses some colliders. thats a serious issue.
I frame by framed Vrisings attack anim, and it looks like damage is dealt BEFORE the animation completes, so it can't be a collider based (on the weapon) and the slash vfx also appears. So it infers that it's a physics overlap or mesh that pops in after a short delay to deal damage.
Like click -> short delay -> damage; while anim starts on click and just finishes when it can.
I plan on making the anims fast and snappy, so the desync shouldn't matter as much. Kinda like Vrising/Hades level of intensity.
Are there any other styles of AoE/crescent type slash detection methods? collider/weapon based seems to be problematic. Though physics overlap has its own drawbacks like manual calls (which apparently is cheaper, since no physics is involved). Any ideas on the best to achieve snappy and semi-accurate feedback? Raycast was also a suggestion*
Use animation events to do direct Physics queries
Lots of enemies you say? Use DOTS hehehe
Does that mean adding events on an anim clip that would call something like a collider toggle on/off?
no like i said direct physics queries
i.e. Physics2D.OverlapXXX or Physics2D.XXXCast
direct queries simplify things by a lot. You don't need to worry about tunneling. You don't need to worry about waiting for a physics update before getting a callback. You do the query and immediately get a result
physics 2d in a 3d space would work? some of the trigger volumes are shorter/taller so weapons may not reach it
o gotcha, that makes sense for 2d*
same answer just with Physics.XXX
sec, trying to read your suggestion again
is it almost like a raycast- but a volume, so in the frame of, it immediately returns if something was hit or not?
What are we talking about here?
There are many different physics queries
some of them use volumes
Ok, i'm trying to get a crescent slash AoE, im assuming that doing a broad stroke volume that just immediately hits everything in a few frames is the way to go, thats the kind of query i want
You can just use OverlapSphere
and then filter out anything that isn't in the correct range of angles
hmm interesting, that would be CONSIDERABLY easier
almost like an explosion check, physics overlap works great for single frames on something like that
you could also simplify it to a Box
the particle effect doesn't have to perfectly match
usually it's good enough to be close
hmmmm, cheap but effective. I could attach the box to a transform and rotate + check every frame like i do now?
or you could do a an array of like 5 overlapspheres in a crescent shape
there are many possibilities
there is no need to "attach" anything to anything
my current physics overlap box stuff (attached to actual weapon w/ anim) works. that should def work
no GameObjects or components required
o gotcha
you just do the math, and call the Physics.OverlapXXX thing
ya im beginning to see now, that's way easier in terms of setup
like the anim/vfx can be totally decoupled and damage is gauranteed
whereas right now, its too reliant on those and its a problem
thanks, that really helps clear things up
on a side note- is there a way to force unity to render animations/scripts simulatenously to prevent desync?
i think i could gate things with a coroutine, and some desync might still occur
that's why I recommended doing this in an Animation Event
that ensures the physics check will happen at the exact moment in the animation you want
ahhhhhhh ok, so the event calls when to begin. rather than a class initializing it. incase the anim is delayed somehow
i was just wondering if its possible to force unity to always do something. iirc time vs time.delta and all that and individuals PC frame rate can hamper things
if there was any syntax to make it gaurantee logic is executed verbatum at a specific time. i will def use anim events
ya, just wanted to see if i could avoid using anims events, since the events get dropped sometimes when i update anims
This is actually super insightful. I love it
the idea was to keep everything in a class to totally decouple it from unity systems, much easier to edit to
i have alot of animations. but i'll stick with anim events for now
If you use an animation event and want it to sync with a fast animation, make sure to do it in lateupdate or at the start of the next frame...
Awesome. I'll have to play with that when I get involved with Unity again.
my packages now dont have a green but a white checkmark, but i only have a remove button for them, not update. and some unlock buttons
yeah that's weird, sounds like there's something fundamentally wrong with your project if you're still not seeing newer versions of those packages available
specifically for which do you see later ones?
collections and unity transport both definitely have newer versions and those are also the ones that were related to your earlier issue
sometimes you need to update your editor patch version to get later versions OR it just refuses to let you go up a major package ver without changing it yourself
e.g. a proj i work on was on cinemachine v2 but to go to v3 i had to change the version myself in packages.json
you can peek in the Version History section for the package
that did it, weird that it doesnt show the update button normally
It probably only shows that to update to the newest patch release
noice
hey there! could somebody give me some help on how youd put together an weapon-altering item system, best example think binding of isaac. basic things like stat changes/character alterations/custom effects
like i know what it all needs to do but the moment i try and code it, it turns into a mess and its easier to start over and try a different approach than to try and fix it 
sounds like something you can do with Scriptable Objects
could you explain more
ill clarify, i dont mean in the sense of what types of objects and classes do i need to create to make items. ive got an intermediate knowledge and plenty of experience so i know the fundmental things like that
composition
i find that sometimes ill extend something too much, try to correct by going the other way and it becomes very stiff
we all have spaghetti code what's new
to an extent i think any system like that will require edge cases
the system was actually fine very early on, but as the dev wanted to add more stuff it wasn't maintainable
well right now i dont have anything besides piles of piles of scripts that are obsolete, I upgraded to 6.0 so a clean slate is nice
If you do want this nice modular system, the best you're going to get is chopping up the behaviours as much as possible
then your choice of a super class or by making unique objects for each one of these weapons and having a custom sequence of logic for each (how all these behaviours are glued together)
Some sort of way to compose an order of execution sounds very nice for something like this
I do think having a object type per weapon is the ideal solution, so this way you can deal with edge cases more discreetly
Isaac, besides the default weapon, has a few different weapon modes which affects a lot of the weapon modifiers
which is why you do need some more handling with how each of those modifiers are applied
Could be worth actually making a little issac mod to get a rough vibe of how that pre-existing workflow is functioning
There is a priority system for each of the weapons, that's for sure. They don't just 'work'
forsure, i assume a fair handful of the dynamics are straight up hardcoded to, no?
eg. some of the brimstone patterns
What I found was that there are 3 main item types that I could extend the way I need
Coin - picking up increments a value
Boost - stored in active slot, manual use
Equipment - a prefab item, like a gun or a hardcoded body modification
its very easy to come up with a lot of other items just from those 3 things, and it also separates a lot of specific behaviour between them
Path of exile is a better example of some modular system, but even that game has a bunch of edge cases
problem is ive been doing this approach for quite a while now, that i worry ive convinced myself that its the best and only way i can do this
but items like weapons have a lot of different ways you could implement them within unity, which probably should make life easier, but its too much choice! š I'm used to a project lead giving strict instructions haha
Well, let's talk about modifiers. Isaac there's a bunch of on hit effects so you'd have a list for each of your weapons like:
List<TriggerOnHit> OnHitTriggers;
So when your weapon hits an enemy you'd cycle through the OnHitTriggers and have like a polymorphic call such as
Trigger(Vector3 position, Entity target)
You don't care what the trigger is, you just care where it happened and the target it has hit so now you can invoke it with what information it was given.
usually id say an event is better for anything to get notified of some thing happening but depends if you wish to return something
e.g. public event Action<Vector3> OnWeaponHit
Right, sending some sort of callback too is nice. I sometimes pass the source too instead of invoking a callback
Any thoughts on how to deal with a weapon and a projectile being two different things? or even if they really should be?
well first off both are just a damage source
I've made a system before where everything was a projectile. Need a lingering area damage effect? Projectile with 0 movespeed
Thats going to be the plan if I figure out if implementing melee type weapons could work
imo you should make something that they both utilise and/or implement
especially if you want more abstract concepts like a radius that damages things inside of it or etc.
previously I had a generic bullet that would read a template from the weapon (mostly just to get a damager value)
what could a weapon and a projectile both utilise?
surely they are too different to have much in common
They are both different in a lot of ways but you wanna focus on what they have in common, which is that they both create a resulting piece of data that is sent to whoever is receiving the damage. This piece of data could be the same concept utilised by both DamageSourceās
do you mean that the hit info should send more than a basic damage value, but also the weapon along with it?
which actually means every bullet is basically just the weapon itself
I have a script for generating a mesh of a circle below an object. It currently is generating the mesh not below the object. it is either off to the side, below, or above the object depending on which object it is. I cant upload it all into the file so i sent a screenshot.
its all in there
I've tried the super class idea and it works despite everything be coupled closely together, but it deals with a lot of comparison logic. It wasn't too bad of an idea, but the worst part was trying to make it look good in the editor because the tools for these types of classes is non-existant.
Could this warning cause any issues? No matter what I do I can't seem to get rid of it.
superclasses are what ive tried to avoid, even though they inevitably appear after enough time š
The HitInfo doesnāt need to have the damagesource directly referenced but a sword and a projectile are the same in the sense that they are just something that produces a hitinfo, just like any environmental hazard like a spike trap etc.
Having this kind of HitInfo middlemanning the conversation between the damage source and damage receiver allows you to control how much information the recipient gets to know.
For example (this might not relevant for the game your specifically making). If you hit an enemy with an electric sword and they are some water enemy who is weak to electricity, they donāt need to know it was an electric sword they just need to know it was an electric damage source. So the sword could convey that information to the hitinfo
What is a super class?
This monstrosity
ohhhh
my comparable experience with that kinda thing would be how source engine does a lot of it's stuff
reason why I hate the shuriken particle system too
āļø
š Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
š Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ok
š Element 0
The way Iāve often seen this sorted out is some generic damageable interface and different weapons use this to communicate with damageable things. Doesnāt matter if itās projectile, melee weapon or lava pit. Of course there will be some generic HitInfo too, but when you need something more special itās easier to expand this. Less need to create some complex megaclasses with gazillion booleans or other conditions
And no matter what kind of system you use, just damage values wont be enough anyway, unless everything uses same vfx and sfx.
Read the server rules, decompiling/modding help isnt allowed here
ight
I keep trying to add in things to make sure there aren't too many indicies for the verticies but nothing ever works. The point in the function where an out of bounds exception happens can change but it never goes away. Idk what I'm just too dumb to understand but there has to be something fundamentally wrong with how I'm doing this right? Or something obvious I'm overlooking?
The current out of bounds issue is on line 58 in blazebin.
https://paste.mod.gg/zcmzboovagpe/0
A tool for sharing your source code with the world!
Having a debugger attached might make it easy to debug as you would be able to see all the variables that led to the error.
Besides your index issue, you should make sure to destroy that mesh and maybe avoid all the allocations and collection copies.
Mesh should be rebuilt every frame in another function unless I did something wrong. As for the allocations and collection copies yeah you're right.
I attached some dubug logs but honestly I'm still pretty lost.
Honestly I'm pretty far out of my depth with this level of programming but if my game will have shadow volumes it needs to be done.
Not logs. Use the Visual studio debugger.
https://streamable.com/jd021o can someone help me with this sound overlapping problem
so i'm not too sure whats happening
heres the gun code
Use Scriptbin to share your code with others quickly and easily.
https://scriptbin.xyz/otaweyisah.cs heres 2 of my scriptable object
Use Scriptbin to share your code with others quickly and easily.
https://scriptbin.xyz/maxinosohe.cs heres my player script
Use Scriptbin to share your code with others quickly and easily.
Based on your Gun script, it looks to me that you could be calling your Shoot function very frequently (assuming PlayerShoot.shootInput happens while the key is still held down, as opposed to activating once on a single press) - based on your output showing your else log, your calling PlaySound very frequently, which looks like it just does a PlayOneShot, which has no knowledge of any already-playing audio - I would suggest to either use Play and a if-check to see if the audio source is still playing, or add a cooldown based on the audio clip length before calling PlayOneShot again
tysm
i just realized that
it works now!
can someone explain to me why when i try use rb.velocity unity tells me to update it after i save it which then auto's it to rb.linearVelocity??
im trying to make a sprite box jump when i hit space, but rb.velocity doesn't work and when i say yes to update it rb.linearVelocity doesnt work either?
nevermind
i fixed it
they changed rb.velocity to rb.linearVelocity in unity 6. as far as i know though, its the same thing, just a rename
Is it possible to use C#'s reflection magic to create state machine graphs from code? As in the connections and what not
Or is this trying to do things the other way around, aka usually you use nodes and graphs to determine statemachine behaviour
reflection magic?
although i am kind of curious too. not sure how to do it myself. you'd probably need an editor extension, but having graph connections in the inspector would make things like dialogue trees a lot easier
yea idk what was wrong but i updated it and its fine now
is there a better way to check for collisions?
private void OnTriggerEnter2D(Collider2D collision)
{
GameObject collider = collision.gameObject;
switch (collider.layer)
{
// Score
case 3:
_score++;
_onScoreChanged?.Invoke(_score);
// Disable so it cannot be triggered twice.
collision.enabled = false;
break;
// Pipes
case 6:
break;
default:
return;
}
}
i suspect this will get really bad when i do a "bigger" game
Better in what way?
You suspect it will get bad in what way?
checking for each layer manually
It's not even clear what script this is or what object it's attached to or what it's doing, etc.
imagine if i have like 10 layers
you should be using the layer interaction matrix to filter the layers
not your code
Depends on a lot of stuff but usually you would be checking for a tag or component on the incoming collision to see what it actually is. Then using the layer interaction matrix to naturally filter what could even show up in your results
i should have worded myself better: does unity have a way to check if a SPECIFIC layer collided? like instead of checking each collision and filtering by layer, i was qondering if theres something like an UnityEvent or something
thats in my player.cs file
The best practice is to do as I mentioned with the interaction matrix
and it can collide with a bunch of things
ill look into it, thank you
you can use the interaction matrix to decide what collisions can happen, you cannot recieve collision callbacks on entire layers though
isee
im not very good with collisions, in my own engine my collision code was just a huge if 
and i never even implemented raycasts
you don't need to implement collisions or raycasts, the engine provides those for you.
yeah i know, i was talking about my own adventure with implementing them in my own engine
an example from something random i have of a more ideal way would be lets say you have a player and theres various interactable objects in the level. the player walks into triggers on those interactable objects to be in range which would look something like
PlayerController
OnTriggerEnter(Collider collider)
if (collider.TryGetComponent(out InteractableBehaviour interactable)
//some logic
This code avoids layers and tags entirely, using a component on the incoming object instead to use as identification and further logic. Butttt we still want to accurately layer all our objects because of the collision matrix. Because these interactablebehaviours only care about the player walking into them for example, we can use the matrix to disable collisions between an Enemy layer and the Interactable layer entirely, because we know we are never interested in checking for that usecase
wait, since when when works in unity too? TIL
case AttackDirection.DOWN when breakDown.Length > 0 ```
it doesn't work in unity, it works in c#. unity doesn't handle it
btw you can use single backticks to get inline code like this
This is LINQ which is a C# feature.
actually, it does work, got no squiggly error lines, and it works as expected
except that I cant use it for default
i didn't say it doesn't work, i mean it doesn't work because of unity
this is a language thing
i don't think this is linq 
it certainly is https://learn.microsoft.com/en-us/dotnet/csharp/linq/
oh sorry
it's almost 5am
it certainly is not https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/when
this is a switch expression lol
linq is for enumerables
lol
i think this is a statement
wait, what do you mean with it doesnt work because of unity? š¤
ah, because I said "in unity too?"
c# - or more accurately, the compiler/runtime, mono - handles syntax
I dont really care who handles it
if it works, it works
just making sure you aren't taking away a flawed understanding of what unity actually does
what are the main methodologies for handling progression game data? For example, having upgradeable units, tech tree etc... take for example a units speed and accuracy, which over the course of the game can have multipliers etc. applied to it... so from then on all instances of that unit use the final updated value etc.... Whilst giving easy access to everything for balancing etc
chat, if i made a matrix/table having lets say photos, and the names within it match a bunch of layermasks, will it work to navigate between teh matrix content from raycasting the layermasks?
dont crosspost
The main methodology is just to code a system that fits your specific use case best.
There are many ways to implement something like that.
For example, letting the unit objects reference some kind of upgrades system and retrieve the upgrade multipliers from it.
Then a tech tree or something would be a separate ui mainly system that would modify the values in the upgrade manager eventually.
i saw this inactive so i figured why not post in unity talk too, ive deleted it from beginner tho
only here and there
define what this is, its called a text chat
what channel can i talk abt a problem im having with unity in?
All of them #šāfind-a-channel
unity talk for general problems i believe
so any idea how this works
yes, but its still best to keep problems in their dedicated channels
Yeah I guess I'm wondering what is the source of truth data set... I could see it being useful to even be an externally accessible spreadhseet/database, if there are established assets/systems for this, rather than making a bit of a custom tangled mess as I'm inexperienced in this more data aspect of gamedev
Anyway, not entirely sure what you are asking.

so, lets say i have a layer mask named variable, and a matrix that has one object named variable in it, can i access it from the layer mask?
using raycast
Well, if you want things to work dynamically, there wouldn't be something like that. You could code to output such a spreadsheet if you really needed it.
Alternatively, you can hardcoded everything manually in a spreadsheet and then sample it at runtime.
what exactly are you implying by "matrix". there's already something in unity called a matrix and i dont think its what you're referring to
matrix as in a table
the massive storing variable, that stores a bunch of items within it
If by matrix you mean a dictionary, then sure, if you have a key, can get the value for that key.
yeah i think you're talking about an array, list, dictionary (or some other data storage type)
there's a lot of ways to store variabels in unity. i dont think a matrix is one of them
i said matrix cause ion know the name in english, but i know matrix is the number storage system, and said someone will figure what i meant
š Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
š Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
GameObjects[] objs;
``` is the right way right
Hi, two questions how can I fix when it hits the ground, it get kind of stuck for a few seconds and how do I make it when it hits the wall it starts climbing it?
the wheel colider it's in the front wheel
you cant 
not with the wheel collider atleast lol
iirc, the wheel collider uses transform.down. it doesn't actually apply forces based on the wheels full body
you'd have to do some weird force shenanigans. probably using the normal of the surface
honestly, this is probably more of a #āļøāphysics question
I did, got ignored
well, its only been a few minutes. the peopel who are generally active in the channel are probably asleep or busy. give people some time to get to it 
This is the coding channel. Where's the question in regards to code?
maybe?
RaycastHit Hit;
Debug.DrawRay(cams.transform.position, cams.transform.TransformDirection(Vector3.forward) * 5, Color.green);
if (Physics.Raycast(cams.transform.position, cams.transform.TransformDirection(Vector3.forward), out Hit, 5, interactable))
{
if (Hit.transform.tag == "Chair")
{
ItemDetect.texture = images[1];
} else if(Hit.transform.tag == "Table")
{
ItemDetect.texture = images[0];
}
else
{
ItemDetect.texture = images[3];
}
}
@cosmic rain ik this is the worst possible way i couldve achieved what i want, but why does it not return the image if its not looking at anything
matrices are math structures that unity has
this is called an array
i figured yeah lol
matrices are 2d
i had to ask chat gpt what was it called
as far as i know, unity only has the matrix4x4. that doesn't store variables though
so help?
(in c#. equivalent or similar structures may be called lists or vectors in other languages)
If it's not looking(hitting) at anything, it wouldn't event enter that if statement.
no structure stores variables, that just kinda doesn't make sense
oh right
any idea to replace them ifs cause its gonna be missy with alat of them
but also yeah iirc 4x4 matrices are important in 3d rendering or smth like that
Add your logic to an outer else if you want to handle cases of not hitting anything.
one other thing now, why cant i register TMP from the editor interface
i meant types. i just said variables since that's what we seemed to be calling them above lol
i did, but like, a lot of ifs wont work out well
Debug it then
you dont get what i mean, it works perfectly rn, but a bunch of ifs will be missy and annoying, is there anyother way to achieve this
might be good to check!
!learn (guh, forgot the command)
:teacher: Unity Learn ā
Over 750 hours of free live and on-demand learning content for all levels of experience!
you seem to be unaware of some of the basic terms used in unity
[SerializeField] TextMeshPro ItemName;
``` so i cant register it from the interface
that's the wrong textmeshpro
this thing
This is not even text mesh pro š¤
no structure stores types specifically im pretty sure
i changed it earlier to check if normal text would work
lists? arrays?
Assuming it's the correct type, you're probably trying to reference a scene object outside of a scene.
so aboga is the tmp and i cant insert it
damn, guess im the one who needs to go check learn 
Are you sure it's the same exact type?
i think you just forgot the word lol
Now enable a debug inspector mode and look at the actual type name.
yeah, my bad. been a while since i've had research all that lol
like i said above, you're using the wrong TextMeshPro in the script
its TextMeshProUGUI not TextMeshPro
the naming is a little confusing, but yeah you just need to replace that
You can use a base class of all text mesh pro text components TMP_Text
i just figured yes
never do I type TextMeshProUGUI anymore..
TMP_Text much easier and quicker to write, also works for multiple UI and Non-UI
huh, neat, never realised you could do that
I'm on like, my third rewrite attempt of an inventory system that does everything I need, and I wanna smack my head against my desk lol
Think this time should probably make a proper list of things to implement rather than blindly coding
It often helps to know what you want to code, before coding it
Does unity 6 have a setting that can enable hot reloading? When I worked in 2022, its possible to save a script during playmode and it applies my changes, but for some reason that isnt happening now
Annoyingly any search for "hot reloading" only brings up links to an asset of the same name, so its hard to find relavent results
What is the formula for Unityās HDR color intensity? I want to set a materialās intensity from script
myCol * intensity I think
No I tried that
you mean you want to set a material value via code?
There are various levels of ""hot reloading"". You can find some behavioural settings regarding play mode and detecting code changes in preferences. Is it not detecting changes?
Yea but the question is different
Someone said * Mathf.Pow(2, intensity) but that doesnt seem to work too
maybe its a Color4?
shader sources are avaliable so you can probably find what it does specifically
its been a while since I touched it
I just remember when I did it on material color * intensity always worked
I did print the color and it gave me smt like (7, 3, 8) etc, values more than 1f
cause i thought intensity read all the values above 1
maybe cause I was using SetColor I think that clamps and reads the rest s intensity ? its been a while lol
changes dont seem to be detected when playing, I can add Debug.Log("test"); to an update which definitely should begin printing, but it only does it when I leave and reenter play mode
Iān using setcolor as well idk
You sure you have a Color and not a Color32?
Are you sure you weren't using some hot reloading plugin? Unity technically can do that, but it's highly unlikely anyone is maintaining their project in a way that survives Unity's hot reloading
Hdrcolor
I believe Unity should by default stop play mode and compile
I printed A specular color with an intensity of 5.5 to see how unity handles it
Isn't that just a Color in code?
I've never needed to use any plugin for it
Preferences -> General -> Script Changes While Playing
aah!
the inbuilt "mid play code reloading" unity has is pretty shit and it only works if all your variables are serialized
dont bother
3rd party plugins to do real hot reload are actually decent
Wdym
There's no type called HdrColor
Yes
Iām editing a textmeshproās local lightning color, which has an intensity value
I looked at the properties and found only _SpecularColor
Which means intensity is somehow inside the specularcolor
Cuz there isnt a _SpecularIntensity property
yeah, thats not a big deal. It's only small changes that I make that I needed it to reload, anything significant I'd always stop playing anyway
but its sorted now
its a big deal when even some of your game verges from what it supports. Then it will reload and your game just breaks š I never use it on any project.
Id like to use the good hot reloading though but need to ask to have it purchased
Pretty sure it doesn't reload just the small changes, but attempts to pretty much reinitialize the whole app with whatever it can serialize, which tends to be incomplete in most projects.
Yea i think only serialized vars get "restored" but ofc the rest of managed memory is lost
hey guys i just got here. working on a science project using the UI system (bad idea i know) I've spent hours on google and the documentation and i am so close to giving up where can I find help
I just mean I could alter a simple like like PlayerHealth -= amount; to be PlayerHealth -= amount * 2f; if I quickly want to test something out
I dont rely on it in order to work, but the convenience it brings for some quick changes without needing to exit and enter playmode, is nice
you could just *2 in the inspector, no?
It's not really about the change itself, but the steps Unity takes to reload any code. Does this actually work in non trivial projects you have?
Making a list of how you want a feature to work is a big help, rewrites happen even with a plan (sometimes for optimization other times for readability/organization) though I found thinking of things in a data-driven way helps me - so ill first think about the most common functionality, then what data or references/dependencies are needed to build that functionality and how I might use that data (can it exist as a serialized class? Should it be a scriptable object to be reused? Do I need to save it to a file?) - then ill think about how to separate the core system (such as managing a list of "slots") and the gameplay features (such as maybe what those slots will accept, like specific "item types") - then I can start thinking of how ill actually build it, which for me is often deciding what patterns make the most sense to use, that way if things change, its not a total rewrite, and adding or removing features is often managing the patterns I chose to use
amount isnt an editor property, that specifically is an argument in a method
is there a help forum?
rip
Why is the UI system a bad idea for what you want to do? What kind of problems are you running into?
there's a unity discussions site and this server
ask you code related questions here right now!
UI is not very well documented.
just right here in general?
this isn't the general channel, this is a code channel
but if it's code related, sure
ok
what do you mean by non trivial projects?
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #šāfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
#š²āui-ux for general UI layout things e.g. how do i use anchors
Just projects with decent amount of stuff going on. I would expect the serialization and deserialization process to break state of most projects
ah, well in that case I have found in the past it feels like it drops changes that really should have been applied
So here's the problem: I am making a gamified task tracking app to track carbon footprint. I am using a UI image as the task button. it opens an overlay based on a specific string stored inside the object. When I instantiate the task, it is unable to store a string and then I am unable to pull the string to open the overlay.
Is this the new ui system or the old one
share here your code for your current attempt: !code
š Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
š Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
if I know a change I'm making is more likely to not count, thats when I just exit playmode like normal
Reject unity, return to Java swing
should I ask in another chat I feel like i'm interupting
No ur good
no. I have left java for many reasons. I am now terrified of java. it haunts me
If ur using the old UI system, it should be easy
I was joking lol
2022.3
nothing is easy when instantiating
that doesn't actually answer that question
No I mean are you putting buttons and texts in your scene from the inspector or are you using the UI document
I'm trying to figure out how to share it well without dumping like, 6 pages of code gimme a sec
In Unity, there is "UI Toolkit" which may be the "new" UI system, and the "Canvas" which may be what you would find in the manual at first
I am using the Canvas system
Then it should be relatively easier. What problem are you having to be exact?
@swift falcon can you share your code specifically where you try to open this other UI and interact with your "new task instance"?
yeah gimme a sec to find it in my horrible organisational system
š
dang unity taking forever to load on old laptop. gimme a few min
ok so its like three scripts interacting how u want me to do this?
well you know what problem you specifically have so show the parts we need to see (e.g. where you open this new UI and try to give it data)
ok sure. Some context, the data that matters is a string parsed with | into two string values and an int
public static int TransformCount;
public int TransformYvalue;
public void CopyTask(string NewTaskData)
{
//do not fix or TOUCH AT ALL if this is touched everything breaks!!!
//do not optomise in fear of project collapse
TransformYvalue = TransformCount * -150; //makes distance farther for every new task
GameObject newbutton = Instantiate(buttonPrefab, new Vector3(0,TransformYvalue,0), Quaternion.identity, buttonParent.transform);//creates new button
newbutton.gameObject.GetComponent<ThisoneVariable>().BString = NewTaskData;
TransformCount ++; //increases distance for next
}
wait you are trying to put multiple bits of data into a string?
its one string
just make a class /monobehaviour to store all your info for a "task"
yea dont do that
what is the better way then so each instantiated object has it's own three bits of data that can then be pulled by another script
public class TaskData
{
public DateTime creation;
public string name;
public int order;
}
you need to go learn c# basics if a class is a new concept to you š
owch. yeah no i learned c# and got an informal cert but I'm bad at using it in unity
haha are you sure
it was a while ago and then i didn't use it for a while... i forgot way too much
i'm sorry.
how do I call the class in my script?
the way i'm doin it right now is... overly complicated
public void OpenOverlay1FromInspector()
{
GameObject ClickedTask = GameObject.FindWithTag("TaskClicked");
string messageAndPoints = ClickedTask.gameObject.GetComponent<ThisoneVariable>().BString;
//^^^finds task that was clicked and takes it's string
string[] splitData = messageAndPoints.Split('|');
string message = splitData[0];
int points = int.Parse(splitData[1]);
string link = splitData[2]; //should set 3rd split value to link
OpenOverlay1(message, points, link);
ClickedTask.gameObject.tag = "Untagged";//untagges tag
}
A MonoBehaviour is a class so give it your data how ever you want.... Via a function or public field or property.
GetComponent<TaskDisplay>().ShowTask(new Task());
yeah no i suck at C#. I can't remember things at all so i'm bad at doin this kinda stuff sorry
Then revise the basics there are plenty of good resources out there
i need to find the time first...
thanks for helping i've spent many hours trying to figure this out on google and in the documentation
Well unity docs won't cover c# language things as it doesn't need to. Check the Microsoft c# tutorials
yeah i was working between those two to figure this out. I should prob scrap that and remake it. But i have no idea how I would do this so it works for any number of unique tasks created from a list of possible tasks...
well if you have a class that holds "task" data then your ui that shows this can be given any instance.
If you need it to be stored on disk for later use then have some save class to hold a list of em:
List<TaskData> allTaskData;. You can use the unity json serialization stuff to easily save/load most data from disk.
use json.net for a better json serializer that supports more types
this is very complicated. My brain is having trouble sorry. So holding all possible task data in a list and then pulling the right one? or assigning the value at instantiation? which do you think is better?
An ideal overview of the app would be on open it loads the saved task data. Each task can have a unique id and you can render a list of all tasks in the UI. The user can click one to view more info and edit a task. They can save the changes and close the window. The user can save all tasks to disk again. Rinse and repeat
I tend to think that with other languages I know, but I don't know C# well yet, as I just began trying to learn it like 3 weeks ago.
hm. that might work. the idea here is the user has 5-7 tasks that are randomly or put in based on what they want and then they try to complete them that day, if they click on them they get info and they can click to complete the task, giving them points, along with a link to the source on why that thing they did or didn't do was good for their carbon footrpint
I don't know why I tend to use one of the hardest things to code when learning a language xD
If you dont need to save lots of data but just what tasks they did complete that is a bit simpler. If tasks are pre made by you then they can be made with scriptable objects!
id honestly scrap this and just start rewriting it. you shouldnt use .Find functions here, or almost ever tbh. if you're manually parsing strings that wasnt direct input from a user, you're doing something wrong
not even which tasks. just a way to create tasks when the app is opened and then when they are clicked open the window with a text block description, a score when you click the complete button, and a link to open the source
bonjour. Ca va?
Server is English only
je parle petit france
i skimmed over a bit, but it sounds like you're trying to create/save data at runtime. should be easy to do with json. Newtonsoft can probably handle what you're doing already
its really like 5 lines of code
can someone explain to me how does rigidbody.drag works
i would love help man. I sadly can't give up on this project and do smth else, as this is my year grade for intro to research
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
⢠Collaboration & Jobs
read the server rules dude
-# hehehe. No. as far as I can tell, that is the best answer. It just doesn't. Good luck man
u should prob delete it too
no?
its against server rules and keeping it up is kinda not the best. might get u banned if u keep it up intentionally, just a friendly warning
i am not very good at french lol
again read the server rules, off topic chat is not allowed
can you show me how? (brb gotta go shovel)
use google, look for newtonsoft and try it on your new class that you create containing the data you want to save
whad the hell is this
rigidbody.drag is very very hard to use
ok i'll try that
do you know what drag is
like, in physics
i cant even see rigidbody.drag in the documentation
it's not called drag in v6
its really not. people just try to use it when they shouldnt
yeah that seems like the more likely answer
like velocity, it was prefixed with linear, and both it and angular drag were renamed to damping
@lean sail u have a sec to help me a tiny bit more to understand how I should use this in my circumstance?
š¤·āāļø have you tried using it
If you feel you are a bit unfamiliar with C#, I would suggest trying w3schools: https://www.w3schools.com/cs/index.php - they have great sandbox-like lessons to learn and practice, then maybe you could try focusing on specific topics that challenge you - if you feel familiar with that content, I would suggest maybe learning about code patterns in C# - Jason Weimann, Infallable Code, git-amend and Terodev are great channels imo that go over using C# patterns in Unity - maybe some of those suggestions could interest @swift falcon as well
...i'm sorry. this project has a lot of weird parts and I want to make sure I'm not wasting my time.
i did codecademy but it doesn't translate well into using Unity
once again, I'm not good at this. I'm just trying to scramble by on the information I have and with many many iterations, but I'm running out of time and am starting to freak out that I might not have this done on time
If your familiar with code patterns already, I think some of those channels might be able to show how you can translate them into Unity, though what you learned in Codecademy should also be able to translate if it is C#, though I can also understand being under a time crunch
it is C# but I was too broke to afford pro to do the projects
yeah no this thing is due in a month or so and i might be fricked (not sure on swearing rules)
You could also try Github, there are lots of free projects to learn from there, including Unity sample projects, the nice thing with Unity is there are lots of resources like blogs and YouTube channels that cover code-alongs and examples of different approaches in Unity (such as using ScriptableObjects as an example)
I've been looking through it, typically my go to site for coding related information.
Big thing I'm noticing, as I have used primarily LUA, structure is quite different, referencing other files functions is VERY different and probably the most confusing thing to me
Maybe this video could help? https://www.youtube.com/watch?v=YEk7mKovpUE - it explains how Unity handles references, though in a simple example, everything works with objects (OOP - Object Oriented Programming), so if you want to access data from another class, you need to know where that other class exists, and thats often done by having a "reference" to it either through the inspector, or through code with Unitys API - though its usually good practice to cache that "reference" in a variable if you use Unitys API such as GetComponent
A few basic ways to get references in Unity.
Directly-
GetComponent 0:38
/GetComponentInChildren
/GetComponentInParent
Public Variable- 3:00
Find- 5:01
Find 5:39 (by name)
FindWithTag 6:14 (by tag)
FindObjectOfType 6:51 (by component)
Interaction- 7:15
OnCollisionEnter
/OnTriggerEnter
Yes
what i described is super easy to do, quite literally a couple of lines of code. just
, people dont generally just help if you arent yet having troubles
and you should really never be paying for code courses online. most of them are shit
the trouble I'm having is that when the thing is copied, it doesn't write correctly and it seems like the best option is scrap and rebuild instead of trying to fix that mess. Sorry for bothering u
im not sure what you're referring to at all "when the thing is copied, it doesn't write correctly". if you're talking about that old code you wrote above, yes you shouldve just started rewriting it by now
well, that's what rb drag is
when I copy the task and try to save the string, i get
object reference not set to instance of object
heres the full error
NullReferenceException: Object reference not set to an instance of an object
ModalWindowController.CopyTask (System.String NewTaskData) (at Assets/Scripts/ModalWindowController.cs:114)
thanks bunches!
actually, "drag" was never really drag. It's been renamed to linearDamping in Unity 6
proper air drag is proportional to the square of your speed
check what ModalWindowController.cs 114 is
I believe the linear damping is linearly proportional
something's null in that line
ah, i see
I haven't carefully tested it, though
newbutton.gameObject.GetComponent<ThisoneVariable>().BString = NewTaskData;
i've rewritten this bit like 10 times idk at this point
newbutton is defined by this:
GameObject newbutton = Instantiate(buttonPrefab, new Vector3(0,TransformYvalue,0), Quaternion.identity, buttonParent.transform);//creates new button
it's probably the GetComponent then
yeah but i can't manage to figure out what the heck is wrong with it. should work according to many hours of googling and the documentation. suggestions?
check if buttonPrefab actually has that Thisonevariable component
try debugging stuff in the code, like right before that line with the NRE, do Debug.Log(newbutton); etc
also if you don't need anything else from the newbutton, you could type buttonPrefab as Thisonevariable, then newbutton would also be a Thisonevariable and you wouldn't need the GetComponent at all
hey wait a minute
those are different newbuttons
GameObject doesn't have a gameObject property
can you show the full file? see below
!code
š Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
š Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
(for context thisonevariable is a script that only has one line, defining a string so i can save a string to each button instance)
Help - i have a IEnumerator Start() where i have yield return new WaitForSeconds(2), but when that line is reached, Unity completely freezes up. Doesn't react to clicks, doesn't update, doesn't pop-up those annoying windows when it's saying that you clicking something is somehow a 20 seconds task...
do I just paste the link for the site?
once you've saved a paste, yes
had to close it with Task Manager again.
can you show some context? (see the above embed)
A tool for sharing your source code with the world!
okay so i wam tired of draging and droping refrences into the inspector
is there a way to resolve that
huh, ok. so apparently GameObject does have a gameObject property, it's just undocumented lmao
resolve... what, exactly?
what do you mean?
No, that is the correct way to do things
that was asking demigod, not you
// Start is called before the first frame update
public IEnumerator Start()
{
paused = true;
LevelData currentLevel = LevelData.CurrentLevel;
//... Some code ...
Debug.Log("Assigned files");
// spawn first notes
notemanager_script.ManualUpdate(0);
Debug.Log("Created first few notes");
yield return new WaitForSeconds(2); // <---- Here
Debug.Log("Waited for 2 seconds");
StartCoroutine(LoadingScreen.Finnished());
Debug.Log("Closed the loading screen");
The last line i see in Debug is Created first few notes. Than unity completely freezes up, like im looking at a static image and not a program window. Zero response.
oh sorry
wait, are you trying to make the start message a coroutine?
i also dont want to write it in awake cuz then it is gonna run everytime i start the game
is it possible that it just stores the refrence there forever once after i start the game cuz write now it loses the reference once i stop the game
yeah i don't think that works
make a separate coroutine that you initialize from Start
that also reduces performane bro getcomponent is heavy task
cuz then it is gonna run everytime i start the game
absolutely not an issue
getcomponent is heavy task
it isn't
Is that not ok? I was told elsewhere that it was.
Once the program is closed everything is gone. You could potentially write it to disk and load it on startup but that would be roughly five orders of magnitude slower than a getcomponent in awake
uh, so you're changing stuff in play mode? that's not gonna get saved
It is, you can do that fine. It's not very commonly used but that's completely doable
coroutines need StartCoroutine to let unity process them. i don't think the start message gets that? 
It does
it does? damn
no like once i do like set it uo now it is ther now i dont need anything
Yeah, this isn't the only one i'm using. This is the first one causing troubles.
And then when you close the game it is no longer there and now you need to do it again
out of curiosity, does that also apply to other messages? awake, onenable, update/lateupdate/fixedupdate...
so what do you think the problem is? (are you still able to help or r u helpin someone else?)
have you done the debugging i mentioned?
this, in case you missed it
i think it got burried gimme a sec
degug log after instantiate or before?
Pretty sure it's just start
This is also a reason why you'd just drag things in whenever you can. Every alternative to it is slower
Hello. This might be a vey basic question, but if I have a list that is
private List<Matrix4x4> matrices = new List<Matrix4x4>();
why is it that doing
matrices[i].SetColumn(3, origin);
is not the same as doing
Matrix4x4 matrix = matrices[i];
matrix.SetColumn(3, origin);
matrices[i] = matrix;
? Like with the first option nothing changes in that Matrix4x4, but with the other option it correctly changes the value
after instantiate, before the line with the NRE
it should come up in the console right?
nothing
matrix4x4 is a struct
did you save and recompile
yes
ahhh okay. Thanks
nothing except for the same error as before. line is 115 now, but that's b/c i put the debug log line in
doesn't even count the log?
the line of the error was the line after instantiate, which was 114. now it is 115
this is inbetween the two:
Debug.Log(newbutton);
bro like when you drag and drop it it stays there forever right
Any time that object is created it'll be created with those values already set
just like that but only once maybe an editor script or something like plugin
712
I'm still not sure what your specific problem is but I can assure you that direct referencing in the inspector is the most efficient and fastest way to reference anything. All other forms of reference should only be used when direct referencing is impossible.
i wanna assign the refrence through code i i dont wanna be drag and dropping stuff but i need the performance of drag and droping stuff
If you need the performance of dragging and dropping, you're going to be dragging and dropping
dont wanna drag and drop cuz there is too many stuff to drag and drop
you're wasting your time by micro-optimizing tbh
The you'd best get started
Use the profiler, you won't even be able to find those GetComponent calls.
okay then as you say
its a mobile game so i thought best to be otimizing as much as i can
did I put the log in correctly? at least something should have shown up right?
Optimization guide:
- Run your game on your target hardware with the profiler
- Identify and attack bottlenecks based on profiler data.
No part of that process is "spend time based on vague feelings of what is or isn't fast"
yeah... maybe put in a log at the start of the function, see if that logs
before instantiate? ok
Good ol' "Move the debug/add more until one shows" to see whats wrong lol
cant use it before it's declared by instantiate
no, just some log as a sanity check
ok
debug logged the Y value variable and this popped up
so debug works then
maybe it's going wrong somewhere within instantiate and therefore won't go past it?
Update - now Unity freezes imidietly when Start is called.
what i am asking is more of a productivity tool
that makes things easier for myself
by not drag and droping things but giving me the performance of it
You should start with GetComponent and circle back to the problem if and when there's a demonstrable performance issue (there won't be)
alright
Ive a bone to pick with C#
why is it that I can't get the teleport function to work like its supposed to!?
i tried the disabling of the movement script, but it still wont move!
configure your !ide first
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
ā¢
Visual Studio (Installed via Unity Hub)
ā¢
Visual Studio (Installed manually)
ā¢
VS Code
ā¢
JetBrains Rider
⢠:question: Other/None
then you did not do it correctly
there are more steps
do you have the Visual Studio Editor package in unity and if so did you regenerate project files?
did you set it in external tools?
no i didnt
so then its not all lol
close VS , set the Editor in dropdown. Click Regen Project files button after that too
did close vs and open script from double click?
yes
screenshot solution explorer in VS
Might not be code but does someone have any idea why enabling shadow cascades mess up the sorting or trails? I can see in the editor they are above a plane, but when testing the game, they are under it (moving them up a bit fixes the problem but lower quality settings don't have shadow cascades so it won't work)
what do you mean solution explorer?
View -> Solution Explorer
right click on it and do reload with dependencies
colors are right again
as I was saying
i cant get this pricking player to change position
so is the log printing ?
iyes
what is PlayerHall
HallwayPlayerMovement
It's one of two controllers
im talking about how do you move
are you using rigidbody or cc
All the other stuff from forums before coming here just said
transform.position = GameObject.transform.positio
you can apply forces or set velocity
This is appropriate for moving an object without physics
that doesnt help me with moving the position of the player at all
This makes no sense at all
HOW IS IT THIS HARD?!
yay, took me 1 hour 50 minutes to find a while loop without yield return null;
In the future you can find these faster by attaching a debugger and pausing execution from the debugger when it freezes, then inspecting the call stack in the debugger
so. the debug log is firing off
what isnt happening is the setting of the new position
must more blood be shed
Either you're setting the position of the wrong object or some other code or component is setting the position back
This is the only bit of code in all the scripts that even involve positions
the rest are just enabling of UI elements and movement scripts
Well you didn't address the first part of my sentence for one
And for two, other components exist besides the ones you wrote
And for three, you might be mistaken about that
I can double check
so right now-
... if its referencing the script, getting the position of the object isnt gonna do anything, is it
I don't know what you mean by that
the floorXDoorX objects are looking for the scripts of the objects
not the gameobject themselves
It depends on, ultimately, which object this chain of references is referring to
what you're calling "scripts" are components, and every component is attached to a game object
It's referring to instances of the scripts that are attached to the actual GameObjects
The question is WHICH ONES
they're pointing at the component of the door gameobjects that allows me to even interact with them
and once I am in range and hit E, it should make it so that the player teleports to the other door
Sure but what are the references assigned to?
... it may just be pointing at the scripts and not the object holding it...
oh i am a brilliant moron
mystery solved
thank you for your time
That's not possible
It's neither of those things.
It's an INSTANCE of the script
so before I just dragged the script from the assets folder into the thing
That wouldn't work
when what I shouldve done was just drag the object holding the script component and make em work
badda bing badda boom, solved
what you're describing is either wrong (if you were dragging in a prefab asset with the relevant component on its root object) or impossible (if you were dragging in a script asset)

thank u
sup gang
is there any way I can make enums inherit like this?
that way I can keep calling my "PlayAnimation" like that
I would love to encapsulate my weapon animations in different structs, I believe
I assume I should switch to dictionaries š¤
because in the long run, when I have more than 10 weapons, it will be a mess
hey maybe this will help you.
https://youtu.be/Db88Bo8sZpA?si=BeL6cDKKkUcveNet
Tutorial of how to manage animations entirely through script in the Unity game engine!
Tired of struggling with the Unity Animator? In this tutorial, I'll show you how to create smooth and efficient animations entirely through scripting, eliminating the need for the Unity Animator once and for all! Say goodbye to clunky animations and hello to ...
if not forget it š
it doesn't matter how you encode your strings, they are still strings and it will be a brittle mess
there is an asset for this kind of animation control (from code) that allows you to make things in a more robust way while retaining some editor conveniences https://kybernetik.com.au/animancer/
that is too long
Hi, I have a problem with the object pool class, I have two different pools in 2 different classes, I run the pool.Clear() method in both of them and the implementation of both is the same.
One of them sends all the created objects back to the pool and clears the objects, while the other does not clear the objects and does not give any error.
What could be the reason?
An example how i implement that two pools
_tilePool = new ObjectPool<GameObject>(CreateTile, GetTile, ReleaseTile, DestroyTile, true, DEFAULT_POOL_CAPACITY, POOL_MAX_SIZE);
private GameObject CreateTile()
{
GameObject tile = Object.Instantiate(DataStorage<AddressableResource>.Instance.ScoreHolderTilePrefab, View.ScoreHolderRectTransform, false);
RectTransform rectTransform = tile.GetComponent<RectTransform>();
GridData scoreHolderGridData = _scoreHolderGridSystem.Controller.Data;
rectTransform.sizeDelta = new Vector2(scoreHolderGridData.CellWidth, scoreHolderGridData.CellHeight);
return tile;
}
private void GetTile(GameObject obj)
{
Debug.Log("Getting tile");
obj.SetActive(true);
}
private void ReleaseTile(GameObject obj)
{
Debug.Log("Releasing tile");
obj.SetActive(false);
}
private void DestroyTile(GameObject obj)
{
Debug.Log("Destroying tile");
Object.Destroy(obj);
}
will i hit a perf penalty from instantaiting a prefab one shot particle system vs holding one and calling emit on it?
if the implementation was the same, it'd function the same for both. there's clearly gonna be a difference somewhere then. maybe you just forgot to assign the action on destroy in the object pool for the 2nd class
m_List count its 0 but there are elements from pool on scene how can that possiable xd
the object is actually removed from the pool when you spawn it, so the list count will go down
i got it
did you maybe just not have any objects in the pool?
i have non released objects in one pool its when i call clear it doesnt do anything but i store the collection of when i get obj from pool .
first if i release one by one all of them then they will be still in scene with non active objects after then i call Clear its worked
Its only clears non active released objects i guess
now i get it š
That video is a fucking blight.
š¤ i dont get what the title of that video means, i skimmed through the video and they're literally using the animator the entire time
Hi guys, i was seeking some help regarding a game mechanic of my game, im replicating the game called brawl stars, and was trying to make the game mode called brawl ball, but im currently struggling with the mechanics and physics around it, such has having a rigidbody on the ball is messing with the player. Currently the ball it self is without a rigidbody, I have 2 colliders on it, one which is isTrigger and slighter bigger radius so it doesnt fall through the floor. Code wise its currently like this
void OnTriggerEnter(Collider other)
{
PlayerController player = other.GetComponent<PlayerController>();
if (player != null && !isHeld)
{
if (player == oldHolder && travelledDistance < 0.5f)
return;
PickupBall(player);
}
else
PickupBall(player);
}
public void PickupBall(PlayerController player)
{
if (isHeld) return;
holder = player;
isHeld = true;
transform.SetParent(player.ballHolder.transform);
}
void Update()
{
if (isShot)
{
transform.position += currentVelocity * Time.deltaTime;
travelledDistance = Vector3.Distance(shotStartPosition, transform.position);
if (Vector3.Distance(shotStartPosition, transform.position) >= maxTravelDistance)
{
StopBall();
}
}
}
one thing i was struggling is when the ball is shot backwards, it re triggers with the same player, but continues to move so its attatched as a child again, but the ball doesnt stop moving so its a mess, if someone could direct me with the right approach to a proper picking up and shooting mechanics, would be awesome!
Unsure about your unwanted behavior but you probably don't want to be doing stuff with player if it's null.cs void OnTriggerEnter(Collider other) { PlayerController player = other.GetComponent<PlayerController>(); if (player == null) return; if (!isHeld) { if (player == oldHolder && travelledDistance < 0.5f) return; } PickupBall(player); }
Woops yea removed the else statement, forgot to when i changed things around with travelledDistance
As for stopping, when should it stop? When held?
If it only stops when it's picked up then perhaps it isn't being picked up.
If so then you'd check on the conditions for it to be picked up.
With the code above it would be player isn't null (the other collider exists and has a player controller component). Or is not held and the collider is that of the same holder with a travel distance of less than half a unit.
do yall know how to apply decals in cs code?
only way i could find is with the weird component
What I meant was lets say I shoot the ball, if i shoot it backwards, it re-triggers the OnTriggerEnter, which is an issue hence why I added the travelledDistance check, not sure if its a good method but it works ig, my current issue with this obviously if I use a rigidbody, it moves the player as well. This also happens without a rigidbody, I can upload a video if you like. but I do need a rigidbody for stuff like bouncing off walls and stuff like that. I dont think I can implement that kind of stuff without it..
Maybe have the collider component disabled for a short duration on initial launch
Unity has a built-in "Decal Projector", and in HDRP there is a Decal shader, otherwise if your using URP, you may need a custom shader AFAIK, though what do you mean by "apply"? Are you trying to set a existing decal to a specific texture or instantiate a prefab with a decal component already attached or enable and reposition a decal that already exists in the scene or something else?
Does anyone know how to keep Rider from doing this? I want both attributes on the same line as the variable but it auto formats https://r2.fivemanage.com/image/d4rX5VTczi8v.png
Anyone know why my follower looks all jittery when the camera moves? Here's my camera movement script:
https://pastebin.com/VFihHgvu
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.
Ye i was thinking that, but i found another solution as well, but im facing another issue currently
If a user catches the ball which was bounced off the wall, it messes up its movement, sometimes even moves the player
void OnTriggerEnter(Collider other)
{
PlayerController player = other.GetComponent<PlayerController>();
if (player != null && !isHeld)
{
StopBall();
PickupBall(player);
}
}
Even though the ball is stopped, then picked up
It could be that it doesnt stop fast enough before PickupBall is called perhaps
I have an inventory system, in the Inventory class, I have an InputAction method that runs the Use method stored in the currently selected item, then deletes the item if it isn't marked as multiUse.
I have a Hand class which manages the visual representation of the items in the players hand, by instantiating a model as a child to the PlayerHand object.
I want to make it so the item in the current slot only gets deleted after an animation on the model of the item ends.
One moment, let me fetch the code.
Here it is: https://hastebin.com/share/lexuzavari.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
guys is ml agents worth still learning or is it dead, as you need many old versions of libraries and its so hard just to set up
Havenāt looked at ur code but sounds like you need an animation event
Hey! Im new to coding and stuff but i was just wondering if anyone would be able to teach me how to make a simple fishing sytem and also maybe a inventory system. if not its ok. Thanks!
try googling those stuff
there's existing resources
Hey y'all. I'm working with getting my movement working using Rigidbodies and AddForce but I've run into the issue with applying force in the direction relative to my player.
I've tried using quaternions to adjust my input vectors MoveDir but to no avail. I know my math is wrong but I'm not sure where I've messed up. Any help is greatly appreciated
Edit: Picture added so it's easier to read
Ah I've solved it. I was using a Vector 3 rotation on a Vector 2 lol
Hello can canyone suggest any tutorial videos to make a 3d puzzle game in unity i am new to this and i want to make a game project at beginner level for my cllge
The unity API and my own ideas have failed me. I need help or advice please
The short version of what I need is that, when a player uses WASD or a gamepad to navigate menu buttons, the game needs to detect it and update a text box with data relating to that text box. I know the EventSystem within Unity knows what object is currently selected, but I am not sure on what is the best way to go about detecting if that object changes.
I have tried some ways to try and accomplish it but most of them either fail or are way, way too janky to be a reasonable option.
One way I thought of is to have the update constantly have a HUGE Case Switch Statement that checks the names of each of the buttons, but this isn't very dynamic and can be prone to becoming even longer if I need to add more buttons to the menu.
Would anyone who has dealt with this system, and knows a more simpler solution?
dont crosspost
Are you using the (new) Unity Input System?
Yes
And it works as intended, my system is able to comfortably control the menu using a Dpad or WASD
Basically, the system navigates through a list of moves, and when a new move is selected, I want a description of the move to appear in a text box, if that gives better context.
Note, I don't want the discription to change when you click on the move, I want it to change when that object is now swapped to be the currently selected object within the unity event system
put a monobehaviour inheriting MonoBehaviour, ISelectHandler, IDeselectHandler (edit: on your buttons) and implement public void OnSelect(BaseEventData eventData) and OnDeselect to show/hide a ui object with this items description
Interesting, I have not seen those behaviours before, I will go read into them a bit more. Thank you very much. š
Well, this attempt at detection does not work.
_textholder returns as a nullref which means that it is not assigned. Which means that the if comparason did not succeed, and I do not know why XD
Wait, no I am a moron, the second statement in the if will never go through as true
AAAAAAGH
Trying again
Nope, still a null ref
try, getting a TextMeshProUGUI component rather than TMP_Text
pretty sure TMP_Text is just the base class of TextMeshProUGUI. i doubt that would cause it
It still causes the null ref.
I'm going to add a few other logs to see where it is not firing
Yeah, that if statement is never triggered.
For context, BattleControlSystem.actionTexts are a list of TMP_Text that are stored. The reason is that they need to change depending on the character's move set.
where's the nre exactly?
I found the problem, I was comparing the wrong list
AAAAG
Small mistakes are my greatest enemy
I saw somewhere that suggested using a single script to control a bunch of objects that have the same behaviour was more efficient than each of them having a copy of said script, and was wondering if this was true? For example moving kinematic objects and what not
don't worry about efficiency until it becomes a problem
focus on getting something that works and makes sense
Unable to get desired values via **Mathf.PerlinNoise **function
I use float parameters
The problem is with scale variable. It doesnt let you control the size of the noise. Basically its all over the place. Using 0.1f is smaller noise than 0.5f, but 0.01f is bigger noise than 0.1f, Doesnt make sense to me
Mathf.PerlinNoise(worldPos.x * scale, worldPos.y * scale) * 2 - 1
scaling the inputs wouldn't change the amplitude of the noise, it'd spread out or squeeze in the entire noise map
Is there no simple way to increase noise size?
what do you mean by noise size?
PerlinNoise always returns a value between 0 and 1
just to confirm, doing * 2 - 1 is going to return a value that is between -1 and 1. Does that sound right for what you want it to do?
Yes
as for size, do you mean that perlin creates a full noise result like shown in the red version on the left (yes its you are getting a 1D value, not 2D, but the principle is the same), but what youd want is to actually get a smaller portion of the full texture and use that, which for the blue would mean that you are zooming in
because thats what worldPos * scale does
Yeah like blue. But i dont feel like i have control over the size. Decreasing/increasing the scale works until it doesnt, at some point it stops getting smaller and gets bigger instead
Hmm, I havent worked with Mathf.PerlinNoise for quite some time, but thinking back to when I did, this does sound familiar
Nevermind i projected it onto a texture and it seems to work correctly
let me check out perlin noise, I'm curious to see something
well, if unity decides to open
hey how can i make a 3rd person character controller like god of war
did
cant find anything good
!learn
:teacher: Unity Learn ā
Over 750 hours of free live and on-demand learning content for all levels of experience!
What kind of keywords did you try googling?
like "god of war like character controller "
Maybe try searching for more general terms, instead of the specific game, try searching the features of a "god of war" character, for example "third person character controller" if your wanting that feature of a god of war character, also adding the keyword "unity" and "c#" can help refine search results
hi
@distant stratus Don't spam multiple channels. Did you read the bot collab message?
ok
Ummmm...do you code in unity
!warn 1320795669744844892 Don't spam the channels. Read community conduct.
frank1215000 has been warned.
Hi I have issue with Unity WebGL I have latest version in Engine but when I package and run it in browser it keeps showing older version even if i remove the cache how to solve this please ?
Using Unity 6
Make sure you've deleted old archive, some apps don't replace with new files by default.
I delete the whole build and make a clean build @sleek bough
do i need to remove some files from the Project's folder ?
Just build into fresh archive and make sure old one replaced where you test it.
I'm doing this already deleting the complete old build and build a new fresh one ..
Thanks you ..
But not useful solution š¦
even tried an Incognito browser same
public override void OnHoverExit()
{
if(!someBool) return;
go.enabled = false;
}
public override void OnHoverExit()
{
go.enabled = false;
}
I know in this case it is negligible because it only gets called rarely but which approach of the two is better?
someBool is only false when go is already disabled, so all the if statement does is prevent the disabled go from being disabled again in this case.
Therefor my main question is which approach would technically perform better? Asking a bool and then only setting it once, or setting it every time it gets called?
Actually, I need a way to detect, in a coroutine, if the animation finished.
Does anyone know what structure the data received from skinnedMeshRenderer.GetVertexBuffer() has? Is it consistent? Is there a method to get it? Thanks in advance
I'm trying to get quads to my shader and Graphics.RenderPrimitivesIndexed with MeshTopology.Quads seems the only way to get there, so I have to manually unpack this data in the shader. (It seemed like using Mesh.SetIndices to MeshTopology.Quads didn't work... unless I messed up something else, which may very well be possible)
This is a coding channel. You should consider asking in #š»āunity-talk if it isn't a coding question to better acquire help
Whatever you do, don't cross post but instead move your post by deleting the post here and posting wherever it needs to be posted #šācode-of-conduct
Does anyone know why i cant connect to unity cloud or use unity version control?
Sign out and back in again and/or try restarting your pc
i got this message
is it not free?
im trying to have a gib that leaves a blood trail on the floor
For some reason I got notified for this message and I was disturbed until I saw the server it was from š¤£
š
Im not sure the built in Decal Projector can do that, if your using HDRP, the Decal shader for that pipeline may be able to do something similar, or you could try using a particle system or VFX Graph, otherwise you could likely create a custom shader, if you prefer using ShaderGraph you might be able to find tutorials about drawing ontop of a mesh to create a "trail-like" effect, otherwise if you prefer HLSL/coding shaders, you could look up "Catlike Coding" who may have some blogs about drawing on meshes for a similar effect - there may be other ways too, though atm that is what comes to mind
ok ill see if i can
How can I get smooth gravity? My jumping and gravity seems too jittery to be smooth
private void UpdateMovement(Transform transform)
{
Vector3 vector = transform.right * MovementInput.x + transform.forward * MovementInput.y;
m_MovementDirection.x = vector.x * CurrentSpeed;
m_MovementDirection.z = vector.z * CurrentSpeed;
if (m_CharacterController && m_ActiveGravity < 0.0f)
{
m_ActiveGravity = 0.0f;
m_MovementDirection.y = -0.27f;
}
else
{
m_ActiveGravity += Physics.gravity.y * m_GravityForce * Time.fixedDeltaTime;
m_MovementDirection.y = m_ActiveGravity;
}
if (MovementDirection.x > 1f)
m_MovementDirection.x = 1f;
if (MovementDirection.x < -1f)
m_MovementDirection.x = -1f;
if (MovementDirection.z > 1f)
m_MovementDirection.z = 1f;
if (MovementDirection.z < -1f)
m_MovementDirection.z = -1f;
CollisionFlags collisionFlags = m_CharacterController.Move(MovementDirection);
if (!m_CharacterController.isGrounded && collisionFlags == CollisionFlags.Above)
{
collisionFlags = m_CharacterController.Move(Vector3.up * -0.1f);
}
}
Even if this was called very frequently, I would imagine the performance impact to still be negligible, though the performance impact will depend on what the property enabled does in its setter, if its only setting the same value (false in your case) to the same variable, then I believe there is no difference since the memory for that bool would not have changed (although the function call would still reach the stack AFAIK) - however, the first approach could be good if the property does more than just set a variable to a value, or when there is other logic that may depend on the bool being true, so it can be a good fail-safe - though, in practice either approach would be a nearly non-measurable micro performance in the worst case
back again trying to solve this issue...
I think I've narrowed down what the problem is, but I'm not sure how to fix it
I am using transform.Translate to move in a controller2D script, but that is not where the issue is
I believe the issue is the way I am applying gravity and maxJumpHeight
during start, I define my gravity and maxJumpHeight based on some predefined numbers and math
gravity = -(2 * maxJumpHeight) / Mathf.Pow(timeToJumpApex, 2); //g = -a2 / b^2
maxJumpVelocity = Mathf.Abs(gravity) * timeToJumpApex;
minJumpVelocity = Mathf.Sqrt(2 * Mathf.Abs(gravity) * minJumpHeight);```
then during update, I do a method that changes my y velocity before it is sent to the controller2D
```cs
public void CapFallSpeed()
{
if (velocity.y > maxFallSpeed)
{
if (!castingModeOn && !meleeAttacks.upHeavy)
{
velocity.y += gravity * Time.deltaTime;
velocity.y = Mathf.Clamp(velocity.y, maxFallSpeed, Mathf.Infinity);
}
else if (castingModeOn)
{
velocity.y += gravity / 4 * Time.deltaTime;
velocity.y = Mathf.Clamp(velocity.y, maxFallSpeed, Mathf.Infinity);
}
}
}```
I think the think causing this issue is that my timeToJumpApex isn't compatible with variable framerates
currently, it is 0.4f, and this gives me the perfect jump height at 30 fps, but if my fps is lower, and frames get skipped, I think what happens is
that I am already done with the timer for reaching timeToJumpApex but I'm not getting the +y velocity from the frames that got skipped
i.e.
lets say I get +1 vertical vecocity every frame
if my framerate is stable and constant, after 10 frames I get +10 velocity
great
but lets say I skip 3 frames in the middle... not a problem, cause I am using Time.deltaTime on the applied gravity so thats
handled... but what if I skip frames 8, 9, 10?
at frame 11, my code says 'ok, timeToJumpApex has been passed, no more +y velocity` without applying the y velocity I should have gotten from those skipped frames
Does anyone know how to do a character selection thing in unity
I have 4 characters, third person, currently using cinemachine free look cam, but that can change if needed. In thinking character selection is like in a tavern, and upon hitting ready you'll spawn into the game
like this
That looks like it should provide you with control over gravity, and similar to this blog, although in this blog they are using a variable for gravity instead of using the global Physics.gravity value: https://gamedevbeginner.com/how-to-jump-in-unity-with-or-without-physics/#character_controller_jump - how are you confirming your jumping and gravity are jittery? Does the same effect happen in the scene view as well or just the game view? Does it also happen at a lower Application.targetFrameRate ? Does the jitter change if you try different values for your gravity and force?
What about this are you struggling with and what code do you have so far?
if youve got 4 different character gameobjects, the easiest thing could be to disable 3 of them, only keeping one active at a time. And whichever one is active is what gets controlled and what the camera follows
when inside the tavern, you'd choose which character to make active
I guess i'm just not understanding how to transfer the camera over to the real scene, let me take some screenshot hold on
I want to toggle a bool that's stored in a material, within a script. Currently I'm trying to do this:
public void CRTEffect()
{
crtMaterial.SetFloat("IsEnabled", Settings.crtEffect ? 1 : 0);
scanlineMaterial.SetFloat("IsEnabled", Settings.crtEffect ? 1 : 0);
}```But this code isn't doing anything
The way I do stuff like that is to give the character a tag called "Player" then you can find the object in the scene with that tag
my follow cam script just finds the player game object in start, so its guarenteed to always focus on the player.
For you, make sure the non-selected characters dont use the Player tag, only using that tag for the selection
That looks correct to me, are you sure the keyword name is "IsEnabled" specifically? Usually shader keywords start with a "_" conventionally
i need help setting up my scene for the main game, because right now after i hit ready, its just a camera that roates to follow my mouse
I was initially using the underscore, but since that also wasn't working, I tried removing it since this is what the shadergraph's generated code looks like:
[ToggleUI]_IsEnabled("IsEnabled", Float) = 0```
I added back the underscore, and it still doesn't seem to do anything.
I added a debug just now, and the one with the "_" does seem to be correct, but it also just refuses to change the float.
crtMaterial.SetFloat("_IsEnabled", Settings.crtEffect ? 1 : 0);
Debug.Log("CRT Is Enabled = " + crtMaterial.GetFloat("_IsEnabled"));```
inside game manager in 2nd scene is a spawn point (which correlates to the teleport system when player walks into the cube on a raft)
what should the cinemachine target be? the spawn too?
I figured out the issue, for some reason the UI toggle isnt actually changing the crtEffect bool. I fixed it.
!code
š Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
š Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
using UnityEngine;
using UnityEngine.SceneManagement;
public class CharacterSelection : MonoBehaviour
{
public GameObject[] characters;
public int selectedCharacter = 0;
private void Start()
{
if (characters.Length > 0)
{
ActivateCharacter(selectedCharacter);
}
}
public void NextCharacter()
DeactivateCharacter(selectedCharacter);
selectedCharacter = (selectedCharacter + 1) % characters.Length;
ActivateCharacter(selectedCharacter);
}
public void PreviousCharacter()
{
DeactivateCharacter(selectedCharacter);
selectedCharacter--;
if (selectedCharacter < 0)
{
selectedCharacter += characters.Length;
}
ActivateCharacter(selectedCharacter);
}
public void OnReadyButtonClicked()
{
PlayerPrefs.SetInt("selectedCharacter", selectedCharacter);
SceneManager.LoadScene("Private Island", LoadSceneMode.Single);
}
private void ActivateCharacter(int index)
{
if (index >= 0 && index < characters.Length)
{
characters[index].SetActive(true);
}
}
private void DeactivateCharacter(int index)
{
if (index >= 0 && index < characters.Length)
{
characters[index].SetActive(false);
}
}
}
is this a good time?
I would imagine youd want to instantiate (or toggle, if they already exist in the scene) your character based on your PlayerPrefs "selectedCharacter", youd then want your target to be set to that instantiated character (if that is the object you want to track and not some specific child transform like the characters head or something)
I need a bit of help disabling a persistent canvas once loaded
Always a good time, dont ask to ask, just ask - if someone knows, they may provide some insight
What is preventing you from disabling the canvas and what have you tried so far?
not preventing
its just not working
so I tried to just disable the canvas itself
since its only purpose is to show a fade to black and fade from black
What do you mean by "not working"? Is your code getting executed? Are you getting any errors or anything?
one second
right so
vid 1 is with the runtime line of code disabled / commented out
vid 2 is with it active, which brings the fade from black animation, but at the cost prohibiting me from interacting with the cnavas holding the moveable objects
like the canvas itself is overriding the raycast
any suggestions?
NEVERMIND
I answered my own question!
is Vector2.Distance really expensive/slow?
i suggested it at one time as an option but was told it was pretty expensive to use
anyway, i was planning to use vector2.distance to adjust the size of an object based on how close to the center the said object was
since im not counting for Z, would it simply be faster to just get an Mathf.abs for subtracting comparing both objects x and y?
If you need the distance between two Vector2s then Vector2.Distance is the fastest option
whoever told you that has a serious misconception of what "expensive" means.
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Vector2.Distance.html
you can see the docs say its the same as (a-b).magnitude. The common advice is if you dont actually need the distance between objects, you can use sqrMagnitude to avoid a square root operation.
ah
for example, sorting based on distance could be solved with the sqrMagnitude if you aren't displaying the distances to the user
i find it funny it was ever said to be "pretty expensive" lol
thank you for clearing this up for me
He's my brother dw
<@&502884371011731486> spam
!mute 1279534456121720955 1d do not use this server for off topic or any other spam
dezert_monke was muted.
in terms of how a cpu works, the concept of "something being slow", more or less is a whole scale that basically has no meaningful impact, especially when it comes to indie game development
one thing might be 10ns slower than another thing, which at face value sounds bad, and if you were writing highly optimised code its a saving that woudl matter, or if you were to call the function thousands of of times at once
you can afford to waste some nanoseconds, especially in an ideal case where youre only calling the function 60 times a second
anytime I worry about optimisation, is less focus on what methods are being called, and more on the actual way im calling/using something. its usually the general code itself thats slowing things down
that raises a good question, I've always heard people say "you shouldnt use X its very slow" but never have i seen anyone actually show actual benchmarks to prove their claim
https://discussions.unity.com/t/which-unity-functions-are-generally-slow-bad-for-performance/70493/2 surely the claims couldnt be a nothing burger
Honestly I can't tell what your point is here (or if you're asking something), theres a few things that you're stating which just doesnt make sense
funny to see Instantiate listed above FindObjectOfType as its the latter that people always point out to say "dont use that its slow" but nobody thinks twice about having a for loop or coroutine frequently instantiate
Instantiate doesn't have any good alternatives
FindObjectOfType does
Well if you need to instantiate something, or many somethings, you need to use Instantiate
anyway as the link you posted says:
Please feel free to add/remove/make suggestions as*** I am only guessing here***:
its been a long day, I might be rambling a little š . my point is just that a lot of people worry about if they shouldnt use something because its slow, but for all intents and purposes, the difference is negligible on a human timescale, especially when it comes to indie game development (excluding some edge cases like high performance netcode)
I agrree that people prematurely optimize
But that also doesn't mean to go out of your way to use slow techniques when it's not hard to do the better thing
thats true, I suppose I overlooked that aspect
Slowness of FindObjectsOfType scales with the amount of objects in your scene, instantiate does not. So it doesnt even make sense to compare them. And of course the speed of Instantiate depends on the complexity of the object
I do find it strange to have never seen any actual benchmarks, it would be interesting to know for sure how things compare
people have done benchmarks, but what exactly do you wish to compare? if you're comparing a .Find function to already having the reference (via like drag or drop, or telling the class what the instance is) then I have news for you which is gonna be faster
As mentioned things scale with the number of objects etc so benchmarks aren't necessarily useful or representative
alright
any suggestions how one might have an event trigger everytime a scene changes from one to another?
Theres an event for that
well, yeah, the benchmarks would need to be comparing like to like
oh ffs this script is doing my head in
people are already generally aware which approach will be faster and tbh in most cases you should be avoiding the .Find functions regardless of its performance. It's not like it's better design wise
if you specify what you're struggling with, people can actually help
oh no Im talking about this
can I not just grab the ChangedActiveScene method from SceneManagement and go about my day?
are you familiar with c# basics, its literally one line to subscribe to SceneManager.activeSceneChanged. then you just have your method declared, which can be ChangedActiveScene if thats the functionality you need
most of that example code is just extra fluff showing what you can do with it
sadly Ive been too traumatized by Linux while studying C to get too cozy with C#
you can just take the event subscription and method declaration, then see what this does. this is the example code without any fluff
public void Start()
{
SceneManager.activeSceneChanged += ChangedActiveScene;
}
private void ChangedActiveScene(Scene current, Scene next)
{
Debug.Log("Scenes: " + current.name + ", " + next.name);
}
don't know how else to share this. So apologies.
Play this itch.io demo - https://andtechstudios.itch.io/protracer
Switch a red/yellow bullet using mouse wheel
Switch to night mode using "2" on your keyboard
Switch to slow-motion using "Z" key.
That smoke tracer effect is what I am aiming for. And I can't find any assets on the store that do that. This one has terrible reviews.
I can't even find good tutorials about this except for tracers that look like laser shots from a star-wars game.
looks like they only draw towards the end of the ray with smoke then lit up the hit with a glow, nothing fancy going on
I would check out the llamaacademy code on this subject, but instead of tracing the entire path limit it to when its close to the hitzone
The whole path of bullet is the smoke trail that gradually fades out
then that makes it even easier
last thing I wanna smooth out for this game, the players are going to be spawned in by instances
how then do I save the instance in a variable in a script?
Instantiate returns the object cloned
For someone who doesn't know how to even begin, can you help me get started please?
I have tried trail renderers, but those look like a the glowing bullet in that screenshot. Not the smokey trail
no, I get that
but one script spawns the instantiation
I want another script to grab that instatiation and store it in themselves
Like I said, the ones from llamaacedmy are good starting point, replace most of it with smoke then get a certain distance from the hit point like hit.distance for a minimum when to commence the glow part. Glow part looks also line renderer just thinned out width at one of the sides
Learn how to show bullet trails, aka bullet tracers to your "hitscan" guns that use Raycast. This easy to implement VFX is a great way to show your players where the bullets are going besides just bullet impacts.
In the tutorial you'll learn how to implement a hitscan gun that does not use rigidbody physics, but instead uses a Raycast to deter...
so make a method or invoke event you can pass the instance into
var instance = instantiate (etc..
OnInstantiatedObj?.Invoke(instance)```
then store them however you want, List or whatever
ive been so confused for 3 days on this, and im confusing myself even more every second. so i have like four different objects in this file. https://paste.ofcode.org/49E3wbGLg3vZdvHvTECZYh I have the parent tree, which has the attached script, and a rigidbody. I have the child of it, a cut area, that is being deformed in code, along with a log cutting object thats a quad with a boxcollider. Im having to do so many transforms and inverse transforms because i want everything to line up. I want to know if im understanding this right, the cutbox is in logcutting localspace for size and center. the cuttingmeshcollider and vertexes of its mesh are in the cut area local space, the raycasts have to happen in world space ie no parent. im getting so overwhelmed at the amount of converts im having to do and i dont really get how to make it simple. (my goal is to get the intersection of the logcutting boxcollider and cutarea, and from those 2 points, turn anything that direction is the same direction as the logcutting compared to the hitoutpoint to be on the intersection between the cutter and the cutarea, not just on the cutter.) is there any right way to accomplish this / do it simply?
is there a way to use 0-360 rotation in code?
there's an issue of euler vs quaternion. in code it seems to be 0-180 then 0-negative180 not 0-360.
having some difficulty figuring out how to solve this.
working on a lockpick system and a random range pie slice is generated (the valid area) but when it falls on angles where the flip occurs (180/-180) the system breaks or doesnt seem to know how to render that. ive been trying to debug draw it so i can see the angle but its confusing
y is 0-360 pretty easily, x starts are 0 and going down is minus, going up is positive
There are a few Mathf methods to help with this
e.g. Mathf.MoveTowardsAngle
this will correctly move towards an angle measured in degrees
have a look at the documentation for Mathf -- there are others
Ok i'll check that out, that may help solve it. its a challenging thing to work out
second line is just an event that Invokes the item spawned.. Its a cleaner version then adding a refrence to each script you want to pass that object through a method
instead of doing
myScript1.Method(instance)```
cause now you need myScript1 inside the script nd any other classes you want to add to, it becomes a mess
I have a Radar script that detects when an object is within range of the player, and displays an icon at the position when a UI ray is at the same angle.
I am experiencing an issue where the icon isn't being displayed at the correct spot, the radar gameobject is 178 pixels to the right on the UI canvas, and the icon is acting like the radar is at the center of the canvas.
This is my code: https://hastebin.com/share/uququdumuj.java
How can I get the icons to display at the correct position?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
OnInstantiatedObj?.Invoke(instance)
so just this?
like how do I format it?
WAIT
OH I SEE IT NOW
its an event , for example you can do Action delegate
public event Action<MyType> OnInstantiatedObj
// inside another class that wants this object
myScriptThatSpawnsStuff.OnInstantiatedObj += Method;
void Method(MyType obj){
Debug.Log($"Hi, I'm {obj.name}");
}```
... oh god I think Im just fried
im seeing whats going on and I understand how it works
I just dont know how to applu that to my stuff
wdym?
cause right now I got a script running to instatite a player object
there is nothing complicated going on here. If you know how to pass objects into methods, its nothing different here.
no no no- its not that
one second
this isnt the way to do it, is it
cause what its basically grabbing at now is a blank game object
huh ? what is this supposed to be
grabbing the instances and storing them in the variables
this isnt a good way at all