#archived-code-general
1 messages Β· Page 364 of 1
I think the confusion here is that those editor windows are OPEN by the time you hit play
even if they're not focused, their functionality still exists
aah, ok I get what you mean now
I'll try
ok now I can enter but now it freezes while in the game (doesn't give me any error, unity just freezes)
try opening a new scene before hitting play
if it doesn't freeze on the empty scene, it means there's a while loop somewhere in your code that causes the freeze
ok ok I think I know which one it is
since it's the only While loop in the whole project
while (!Overlaps)
{
RandomVector = new Vector2(Random.Range(PolygonBounds.min.x, PolygonBounds.max.x), (Random.Range(PolygonBounds.min.y, PolygonBounds.max.y)));
if (Physics2D.OverlapPoint(RandomVector) == Polygon)
{
Overlaps = true;
}
}```
it's to pick a point inside a collider
nice!
not sure what you're trying to do there tbh
just find a random visible point of the Polygon in the scene?
oh it's for a movement thing
so I make an area with a polygon collider trigger
and set a random point within said area to be the next point a character moves to
yeah I don't like that design π
So this wouldn't work because the point it would find might be behind a wall, right?
while (Polygon.OverlapPoint(RandomVector)) { RandomVector = ... }
yeah, basically what I'm trying to make sure is that the point is inside the trigger
then try this ^
and I'm doing it like this so that the point is inside the polygon, since otherwise it'd check the whole box
oh
ok I was readidng it a bit wrong
np
wait wait, but RandomVector isn't set yet before the while (it's just Vector2.Zero beforehand). So the while would be skipped since Polygon.OverlapPoint(RandomVector) would be false by default
unless it overlaps with Vector2.Zero, which isn't the case
I would likely do it like so:
while (!polygon.OverlapPoint(pos)) { pos = (polygon.ClosestPoint(pos) + (Vector2) polygon.bounds.center) / 2f; }
yeah my bad I meant to type while (!Polygon.OverlapPoint(RandomVector))
hey guys, I need some help
I create a Dictionary<string, int> table
The player input "abc" for example how do I split it out and add it indivually? like
table.Add("a", 0)
table.Add("b",0)
table.Add("c",0) automatically?
Someone?
Alternatively just treat "no entry" as if it is 0.
I am sorry, I do not know what you are saying. Can you describe the issue a bit more?
Totally! First person camera game, I am doing that where you look you add a knot to a spline (so an object after will follow that spline with spline animation) but instead of adding the spline where the ray hits it is added with the coordinates a βββlittleββββ bit to the right
Ahhh ok I see. I am not experienced with splines, but I think that explanation will help anyone that is. The raycasting logic looks fine to me though. And since it is a flat plane (it looks like), setting y should not mess it up.
Imo it must be something to do with how the splines themselves work, so beyond what I can help with.
guys I got another question, How do you convert Base64 to Base10, like I have a character name and I want to get Base10 number
Sorry but that makes no sense, Base64 is a string how would you expect that to ever be convertible to a number?
ah sorry I meant Base62
Still not quite sure what you are trying to do but this may help
https://www.codeproject.com/Articles/1076295/Base-Encode
A Base62 encoding algorithm with a special prefixed code for utilizing Base64 schema in Java
!code
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To 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.
I have an issue in Unity: how can I use the SaveProgress method from the SaveLoadSystem class, which is registered as AsSingle, in various parts of the project without creating circular dependencies? In the loading scene, the LoadingPlayerProgressState is used, which applies SaveLoadSystem to load data from the GameProgress class. How can I use the SaveProgress method while avoiding circular dependencies?
https://gdl.space/ecuzefodom.cs
https://gdl.space/ijusequdem.cs
In other words, I can have only one instance of this class in each scene. For example, in GameHub, GamePlay, only one class can handle this, but the issue is circular dependency.
Note : Zenject : DI Part
private void BindSaveLoadService()
{
Container
.BindInterfacesAndSelfTo<SaveLoadService>()
.AsSingle();
}
You was totally right, it was that, the .add of the Knotes are float3-local coordinates not world coordinates
Working!!!
I'm working on a map editor and I'm trying to figure out how to detect when the map was modified, which just means a child within a certain gameObject has changed position, one has been added, or one has been removed, thoughts?
nvm i figured out i can just track when objects are added or selected
Is it ok to pile up random methods as extensions (on Transform for example?) Is there a better spot to put this code?
I'm implementing an interaction system with handler components for different interactables, so the component extends Monobehaviour, IInteractable but now that I have 2 of them I wanted both to animate the character turning towards the interactable. I moved this animation code to my static extension class, but I found myself wondering where should I put common code for interactables (I think I went down this road before and found that Interfaces can actually contain non abstract code but it's not recommended?)
What is the better way to pause a game in Unity than the one I will mention after this question ? I have thought of using enum as states of the game and an event which can be used for subscribing and unsubscribing to the scripts which need them, plus it will be singelton.
just pick whatever if it turns out to be a problem you'll refactor it later. I've used the event approach in my first game and will continue to do so, although not a lot is happening in my games (just show the pause menu, timeScale = 0, etc. but if you need anything else your event is right there ready to hook other stuff into.
I'm not sure if this is like, where this goes, or what exactly I'm doing but..
Long story short, I have no experience in coding and want to pick up Unity for a 2D Sprite-based Mystery Dungeon Project I plan on making. I have no idea where to start, I've googled "How to get started in Unity" but am met with choice paralysis with the amount of guides that show up.
I don't know what kind of things I need to learn or where I would even begin, so I guess I'm hoping for.. general advice? Where to start? What videos are good to watch? What kind of resources are available to me?
Literally anything is appreciated. ^^;
Unity Objects are extremely bloated already, extensions like DoTween that target high-level objects like Transform, GameObject and MonoBehaviour bloat it even more.
If your goal is system-specific, I'd advise adding the extensions to the specific system (e.g.: IInteractable), which is superb, or even just add them as default method code if feasible.
not a great question format lol. Just tell the way you use first next time xD
find a flappy bird tutorial and follow along from start to finish, you'll get familiar with a lot of unity concepts along the way and some will be applicable to the actual game you want to make.
Okay.
Thank you! I'll try that o:
Best question format imo: What you're trying to solve --> Description of the problem --> Additional info that may help speed up the convo
The way you're describing is on the right track for properly pausing a game. But could go with something like:
public interface IPausableObject {
void Pause();
void Unpause();
}
```and implement it to your pausable objects, then with your singleton, when the game is paused, you could do:
```cs
var pausableObjects = UnityEngine.Object.FindObjectsOfType<IPauseableObject>();
foreach (var obj in pausableObjects) { obj.Pause(); }
Thanks for the help.
np
making Time.timeScale = 0 also pauses all physics systems
Thanks. I will keep that in mind.
Anyone knows why suddenly when I create a new script it jsut doesnt use unity
everything was fine like a min ago
I get issues when trying to get the gun component. CustomHVRGunBase is derived from HVRGunBase which is derived from HVRDamageProvider
public override void HandleDamageProvider(HVRDamageProvider damageProvider, Vector3 hitPoint, Vector3 direction)
{
base.HandleDamageProvider(damageProvider, hitPoint, direction);
gun = damageProvider as CustomHVRGunBase;
}
can you post pictures of the definition of those classes/interfaces? (just the public class x : b part)
and what are the issues? it should at least compile as long as there's a variable called gun declared in your class
the issue is that gun is null
I shoot the guy with the CustomHVRGunBase, it registers the shot, but gun isn't properly set and remains null
have you checked that damageProvider isn't null? or printed its type beforehand?
Alright so turns out a setting was enabled that uses the guns ammo as the damage provider. I did something similar before so I was confused why it suddenly didn't work anymore, thanks for the help.
np
Hi. Does anyone know how can I add a class to a list of its own type but with a method that doesn't specify which class is it?
Like I have the following script:
public Dictionary<int, ThingsOfEachTeam> DictionaryOfThingsOfEachTeam = new();
public void AddThingToTeamDictionary<T>(int team, T thing)
{
if(!DictionaryOfThingsOfEachTeam.ContainsKey(team))
{
DictionaryOfThingsOfEachTeam.Add(team, new ThingsOfEachTeam());
}
ThingsOfEachTeam each = DictionaryOfThingsOfEachTeam[team];
switch(typeof(T))
{
case Type t when t == typeof(FuelConnectorScript):
if(!each.FuelTankerConnectors.Contains((FuelConnectorScript)thing))
{
}
break;
}
}
}
[System.Serializable]
public class ThingsOfEachTeam
{
public List<FuelConnectorScript> FuelTankerConnectors = new();
}
And in the part of "if(!each.FuelTankerConnectors.Contains((FuelConnectorScript)thing))" it says an error because Cannot convert type 'T' to 'FuelConnectorScript'
you need to constrain your generic with a where clause
Oh okay. Thanks
How can I "reset" a 2 bone IK rig? I have it work correctly for my character to press buttons, the hand is exactly where the ik target object is, but after I reparent that ik target transform (for another interaction where I want the characters hand to touch a moving object) it get's offset? I reparent it, set it's position to it's original position. I call Build() on the RigBuilder component, but something is still off.
i've got some descriptive XML code that informs that I need to use it in OnGizmo's but before i noticed it I had forgotten..
Is it possible to have the IDE error it out w/ some type of message if its not in a "OnDrawGizmos()"
if sooo, is it straight forward or pretty complicated?
if its not, thats fine too, no big deal.. just experimenting for now
You can build in custom C# analyzers that show warnings or errors for all sorts of stuff, but it's pretty complicated (probably like an 8 or 9 out of 10). Not sure if there's an easier way (or what kind of gotchas there might be in the context of Unity project). https://learn.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/tutorials/how-to-write-csharp-analyzer-code-fix
i want that lizardman kills pigman but pigman dont want to die can someone help me
Do not post the same question in multiple channels.
Context missing, please see below for info on how to !ask a question
: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
there is not missing anything lizardman moves and wants to kill pigman but pigman dont die
We are not in front of your screen, therefore we do not know what you're talking about
Hence why you need to provide the full context along with your question
Continue discussion in #π»βcode-beginner.
[this answer](#archived-code-general message) should help you, but I wonder whether you really need it, since I haven't seen Unity's Gizmos methods throwing warnings like this
thanks! i'lll check it out. (just procrastination of sorts)
like here, no errors or anything.. but they wont be visible in scene.
if i just put it in a OnDraw call.. they do.. (with a few gizmo's laying around its hard to tell from first glance if anything is missing)
just curious if there was a way to make it noticeable in IDE before i went and recompile everything
- if i figure it out, i know of a few other places it'll actually come in handy
ahh, i missed this.. thanks.. i'll give it a read.. (even if its outside my scope, can't hurt to see what type of things are possible)
Actually analyzers use Roslyn and Unity uses Mono? So that might be impossible (what I linked).
I've linked this answer though
#archived-code-general message
ya i seen that too. and responded, more the merrier.. im on a mission to read and learn today..
Hello good people, I have an animation clip, and a curve, and i want to assign the curve to this clip?
clip.SetCurve("", typeof(Transform), "localEulerAnglesRaw.y", rotationYCurve);
I have been trying this, but it does not seem to work
Any ideas please?
localEulerAnglesRaw does not seem to be a thing in Transform. Even from the source code, there's no private member called that
Aah I did not know,
I was following this. But looks like I cant just add a curve to an animation. Let me try some other ways
Try localEulerAngles which is accessible
I tried that too!
But the thing is I used EditorWindow to generate curves in bulk, just wanna transfer them to the clip if that makes sense
some serialization issue maybe
for the Y rotation
Okay so the link you posted here should accept localEulerAnglesRaw just fine (in the source code, it pre-processes the value silently, which is what confused me), so the issue is likely elsewhere
it actually doesn't have anything to do with reparenting, I removed the parent manipulation and it's still off, I think it's because I manipulate the rig constraint values via an animator controller. I've seen posts around the web saying weights should only be manipulated in Update?
my trigger event to lower the camera isnt working even tho i have everything set up correctly after double checking
https://pastebin.com/LQuruR0w
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.
any help is much appreciated
I can't see you actually assigning the lerped y to anything?
^ true
in cases like this i'd recommend either going into debug mode or just putting in a bunch of debug.logs to check if all the values are correct
Unsure which channel this would fit? Is there any guide for picking up unity for someone already well endowed on the technical field? I can code and i generally know how 3d spaces work but all the resources i can find involving unity are meant for someone totally new to anything technical it seems
I say this because most of the stuff I learn have some document for estabilshed developers (If i recall Typescript documentation has specific introductions for JS, C#/Java and Functional progammers as an alternative)
!learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
Sounds like you just want the !docs honestly
If you go with learn, you could do just essentials and common core
Skipping junior programmer
I kinda want something inbetween, docs is just trial and error until i stick while learn is like extremely below my level
The two pathways I mentioned introduce you to ONLY editor specific concepts
Also, look at CatlikeCoding
Probably just go with learn and skim over things you already know. There are also some differences in how code is usually written in Unity compared to a regular .NET project.
i dont think there is a inbetween, its either or
I assume so, because all the game engine code i stumble upon always looks like a spicy version of normal code
that is, except for C++ games
you're just consuming an API, c# is the language chosen
game engine code is a wrong term to use, code meant to be used for a game engine is more proper, but yeah
API code always is the spicier version
It just ocasionally has macros in it that make it look weird
By macros, you mean preprocessor directives? C# doesn't have macros.
I mean stuff to let the engine know to expose your values and stuff. It's outside the standard syntax
Ah, you mean attributes then i assume?
Otherwise it is the same
Yep. haven't messed w it on Unity yet but i tried on Unreal and it was quite different from standard syntax
Well.... that is unreal haha
I would strongly agree with you in that case.
That is one of the differences between unreal and unity
it almost seems like unreal tries for the developers to avoid using C++ lol
Macros are an inevitable part of C++. Though, I'd agree that they complicate things up.
Yeah don't judge Unity based on viewing some Unreal code, the two engines are very different and they also use two different languages.
The reason i say this is i know Unity has also a bit of a strange syntax involving the same purpose as far as i remember. Unsure if they changed it
Nope, C# is C#, there's no strange syntax you can add.
I do not remember this in the last decade. 5 had some weird stuff I may be forgetting though
Unconventional usages of existing C# syntaxes, sure you could argue that.
And even that is not forced or necessary
Oh yeah, it's c#. that's part of the spec, it just looks wrong
Everytime I add a new system/feature I use Debug.Log and Debug.LogError to show it in console. Sometimes it clutters up to 20 or 30+ messages so I remove some of the extra lines... Does it affect the final build performance if we use a lot of debug.log. I don't want to remove all of them as sometimes I want to know when something is started/stopped.
you can press collapse in the console to get rid of the clutter
and usually when you game is done you get rid of debug logs
Yes it does affect performance if your logs are included in a "development mode" build, since its constantly writing to a file for every log thats output, however for a build you intended to release to others, you can disable logging: https://docs.unity3d.com/ScriptReference/ILogger-logEnabled.html - alternatively, you could set up your own event logger so you can still know when things get turned on and off without writing to a file until a specific point (like maybe between scene loads), I do something similar for my multiplayer game during playtests
I think debug logs are disabled in a non dev build. Could be wrong.
Oh, maybe I am wrong.
- You shouldn't be moving rbs with transform if you expect physically correct behavior (like not missing collisions)@plain halo
Move it in a physically compatible way.
Looks to me like in the error3 video, the ball is actually bouncing off the back wall. When you turn that collider off, what are you expecting the ball to collide with?
I knew that when the bot missed the ball could bounce off the wall, but I thought that when it went to the bot's paddle, it did βcollideβ. But apparently it doesn't
@cosmic rain don't u ever sleep? lol
Yes, at night
Timezones
It doesn't look like you have a collider on the paddle at all
The composite is just an aggregate of other colliders, but not a collider itself
- MovePosition needs to be called from fixed update.
Should I add a custom collider? I thought the composite was a collider
But yeah, a composite collider alone is also an issue
is the reason why unity insists on floats over doubles just because it's own code uses a lot of instances of floats?
I wrote it inside FixedUpdate
I assume so
Floats are typically used by default in game engines, as you want to minimize memory consumption.
I would just add a box collider
you dont really need double in most cases, when float is sufficient
I used a box collider before, but sometimes the ball bounced strangely because it just collided with a corner of the box collider. It's a completely 2D game
It just irks me that it seems like every resource online simply ignores the existance of the double because the float data type is not going to be sufficient if you want to be reasonably precise
It's gonna be pretty precise. It really depends on your use case.
Double is not a cure to imprecision. It's just gonna have less of it.
The other options are a polygon collider so you can 'round' the corners or something to make the ball bounce like you expect. Or you can make the box collider a trigger and handle the bounce-back yourself in OnTriggerEnter2d
well its not like theres some hidden knowledge you need to use one or the other. if you want to use double then use it. the math is the same
also even if you use double, you still need to convert to float to use it in unity. so you can never read back those float values otherwise you lose precision
i understand why they pull floats as the common one because youre most likely using them for 3d vectors. but sometimes the decimal values you want are needing to be precise
this sounds like a "i dont think itll work" rather than having an actual issue also
but the resources never just talk about them, it's odd
floats lose integer precision at the puny value of 16 million
You might also be able to use an edgecollider2d. But I haven't had the exact problem you're having. What I can say is that you need to fix the collider problem. That's the way to fix the overall issue
But what i'm referring to isnt just focused to the engine overall, it's just that for some odd reason it's more common to represent every decimal notation as float no matter the use case. The resources i've spend this evening reading never seem to appoint to the double being used
just curious did you even read the responses to you?
I see no need to use doubles in almost any circumstance
There are a few cases here and there, but they are quite rare
use rb.position instead of transform.position to stick to just the physics engine but otherwise looks good!
Yes i did and i know why floats are chosen technically wise.
I speak as an outsider to the game engine world 32bit floating point is evil and almost all SWEs avoid it besides when you need it such as in the case for repeated use (such as transforms)
actually we'll always have at least ONE high-precision-needing thingy in a game, so dunno..
Wait till you see halfs and stuff
but from what i've read on unity documentation, it's always floats
Well since unity uses floats, if you use doubles then you will always as some point lose that precision when interfacing with the unity api. So, you lose out in memory, and need to cast back and forth. So yeah, always use floats unless absolutely required for something that doesn't ever touch unity (or if it is only copied I guess)
In games imprecision can often be forgiven, as the player would rarely see it's effects. On the other hand, a player would definitely see if the game tanks their hardware.
Remember, it doesn't matter how precise your calculations are if they wouldn't have an effect on the player.
I tried again with BoxCollider and now it works correctly. I didn't think it would be so easy to fix it haha
it's slightly annoying to place a scaled UI object on 0 and see it get moved to -0.058086e-5 according to the inspector
Tomorrow I will try the collider ideas you suggest
my issue has always been intervals and not the actual precision of the number itself
the difference between the two values is just not good enough
Can you give an example?
By the way, if I have any questions, can I write to the DM?
but yeah there are practices specifically crafted to account for precision, (e.g.: Mathf.Approximately(..) hasn't ever failed me)
as i've said integer precision, on just 16 million youre moving on a basis of 2 integers at a time
perfectly reasonable compromise for let's say position since youre saving a lot of performance but theres cases where that step value might cause headaches to deal with
plus really large numbers are another case
even though i wouldnt stop at a double for that
Well yeah, position gets floating pointed pretty soon, but most games solve it with a floating origin. It's not like a double is gonna solve the issue completely. Just gonna delay it.
Yeah and i'm not going to bother talking about that issue since it's reasonable to compromise there
And the only games that need that are usually games with infinite worlds or close to that.
You know, a floating point number isn't only strictly locked to be for positions...
Indeed, but you rarely need to use it for such huge ranges.
I've had plenty of cases I used it for reasonable applications
And if you do, there's probably a solution for that as well
Game applications?
I'd like to hear a case.
more abstract, like algorithmical applications
if you want a classic case for a game application you could easily mention a simple case such as an extremely huge number
If you need precision in an algorithm, you can freely use a double. No one is preventing you from doing that.
That's not an example at all.
What would that huge number be used for?
You have plenty of games (and game genres) reliant on huge values
an example would be Cookie Clicker
A cookie clicker would break with doubles almost as much as with floats.π
As I said, doubles are not a fix.
Every memory scale up follows the inverse square law...
I don't see how that's related to the conversation
the game goes from a puny 10^60ish to a 10^300 max value
That's the max value, not when the floating point starts to break things. Weren't you talking about floating point error?
there's multiple problems involving a floating point numbers, i just named both my biggest issue with them and then an example of usage you asked me about.
mind that integers (.. and all other types) are consisted of tons of bools/bits, lol (and an algorithm).
float algorithm just happened to be the best engineers could achieve for apps that also utilize the GPU.
You can surely architect a NumberUpToInfinite class/struct that will be precise if you put effort into it.
yeah, you can always implement a quad floating point number
or even better, assign the mantissa to a int64
The point is that these are very specific niche use cases, where it is your responsibility to decide what data type to use.
the example for big numbers for games is these games involving lots of resources typically achieve the biggest float number quite easily, however they nearly never achieve the largest double number
if we were using double in Unity for transform or whatever, rendering operations on the GPU would be much slower coz GPUs aren't doing that well on 64bit as they do on 32bit
I wouldn't store resources as floating point numbers in the first place.
I've already recgonized that double is probably not wise to use in-engine wise. never had a problem with that. I only really was talking about how it's seemingly disregarded for the introductory resources that the data type exists
for the case of a big number game storing it as int will get quickly inefficient
That's part of learning the programming language. Open the C# manual and you'll see them introduce it very early.
again, inverse square law
Not if you want to avoid floating point error.
for this example there's a nuance. I don't think either me or you care about continuing about the big number game example though
that said I don't think anyone here believes double is useless.. all we're saying is fp32 precision is enough for the reasons it's needed.
we can even serialize double on the inspector or use it for your operations or whatever.. it's just the stuff related to transform that are strategically locked to float
It's not that i think any of you find it useless, i just find it very intiguing how people here are just very opposite to the sentiment in SWE where doubles are almost always common practice to use instead of floats whenever possible
how it's seemingly disregarded for the introductory resources that the data type exists
yeah well I guess the tutorial people couldn't find any uses to introduce them, or were afraid of introducing them without predecessors π
like for example I'm pretty sure I've seen the ballsy SebLague use them naturally
It's like the floats are your defaults and doubles are luxuries, while in the SWE space i've looked out for, the double is the default and the float is the compromise
He has very algorithmical content, makes sense for him to go to max size directly
that's not a bad observation lol. I just realized I also use them on non-Unity apps now
(e.g. WPF where the default precision is double xD I go out of my way to cast float to double before using the engine π€£ )
@cerulean yarrow what's that SWE space you're talking about?
as in overall SWE i have interacted with
Well, it is. 32 bit precision is the default in gamedev.
the field
as in, what's SWE
software engineering
Software engineering includes many different fields. Perhaps the one that you have experience in uses doubles mostly. But there are many more fields that have different common data types.
I would like to affirm it is the most common sentiment
Well, then consider that you've finally found a software engineering field that doesn't conform with that sentiment.
what is the cheapest way (in terms of RAM usage) to save down a 2D texture into ur local storage
File.WriteAllBytes(filePath, downloadedTexture.EncodeToPNG());```
i used this
looks fine to me
EncodeToPNG() doubles+ the memory requirement for the scope but doing it for one texture at a time shouldn't have any real impact to RAM π
Does anyone know whether URP/HDRP would realistically be any good for a 3D low-poly-ish game? Any benefits etc.
What is a decent damage dealer / damage taker architecture?
What im thinking is having Damageable / DamageDealer components.
The damageable component requires a collider trigger, and the DamageDealer component creates a collider upon attacking, which it removes after the attack. (The alternative would be to always have it there, and check whether or not the colliding gameobject is actually attacking and not colliding by accident)
The DamageDealer component is responsible for calculating outgoing damage (player buffs, weapon stats), and the Damageable component takes the outgoing damage and applies defensive calculations (armor, etc).
The Damageable component would house the GO's hitpoints.
The collision also raises an event for the VFXManager, SFXManager, to listen to.
That's about it, is there anything that you thing can be done better?
this function is inside a loop , i counted and it will iterate 47 times
but yeah, each iteration only doing one pic
yeah it's fine if you're not caching the EncodeToPNG() bytes inside an array or smth. Still a little dangerous RAM-wise since it's fullAlloc but it's gonna be fiiiiine
niiice
p.s
previous dude was using filestream to create a new file
and then get raw texture data from that 2D image, and write to that file
each time when that function is executed, 100% out of memory
like the usage is EXPLODING
the peak usage was 4.1GB
proven good hire π
lmao
Either IDamageable (interface) or Damageable (component) is fine. I'm a little concerned about the DamageDealer being a component, though.
I'd suggest going with IDamageDealer, so you can plug it into any existing class
-- which could be either a Component that handles enemy combat, a static object (e.g.: Thorny Bush), or even a Usable item
thus after reaching this conclusion, I'd also vouch for IDamageable for the sake of consistency and same level of extensibility across the system.
the interfaces would just be like this:
interface IDamageable {
Action<float, IDamageDealer> OnDamaged { get; set; }
void TakeDamage(float dmg, IDamageDealer damager) => OnDamaged?.Invoke(dmg, damager);
}
interface IDamageDealer {
Action<int, IDamageable> OnDamageDealt { get; set; }
float CalculateDamageToDeal(IDamageable damageable);
void DealDamage(float dmg, IDamageable damageable) {
var dmgToDeal = CalculateDamageToDeal(damageable);
damageable.TakeDamage(dmgToDeal, this);
OnDamageDealt?.Invoke(dmgToDeal, damageable);
}
}
!code
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To 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.
Hey, why when I use StopCoroutine while WaitForSeconds is processing, it will still invoke the event after the settled time?
@hidden nacelle how are you starting and stopping the coroutine? the correct way is:
cr = StartCoroutine(SpawnKeyTimer());
StopCoroutine(cr);
What am I doing wrong here, it says that you cant convert int to ulong?
DOTween.To(() => horizontalGroup.padding.left + 100,
x => {
var padding = horizontalGroup.padding;
padding.left = x;
horizontalGroup.padding = padding;
},
currentPadding,
.5f)
.OnUpdate(() => horizontalGroup.SetLayoutHorizontal())
.SetEase(Ease.OutQuad);
What says? Show the full error
nvm I just figured it out. I had to do padding.left = Mathf.RountToInt(x)
It didn't work even with your way, but it worked with StopAllCoroutines()
Because you've done it wrong
The started coroutine should be assigned to the global variable of type Coroutine
I did exactly like this. Created a field of type Coroutine, valued it in Awake() (cr = StartCoroutine(SpawnKeyTimer());) and tried to stop it with StopCoroutine(cr);, but it still didn't work.
Have you tried stopping it from another script?
And, please, show the code
All in the same script
It starts normally, and logs everything
The Coroutine shoudl be stopped if OnTriggerEnter is triggered
It doesn't stop and invoke the event after settled time.
did you mean to have a cr =... on that last line?
And the Coroutine is started again in OnTriggerEnter
As simonp has mentioned, without the assignment to the variable
Also, you have to check for cr being null before stopping it, since it's going to throw an error if it is
Anyone?
It's just a hard coded array in this internal editor class.
https://github.com/Unity-Technologies/UnityCsReference/blob/0782d04c6768dd2e380c64007baf165f2033e867/Modules/TerrainEditor/TerrainInspector.cs#L241
for a script that manages health, should i make it both the enemies and the player's health, just with a bool to check if its the player or not to do player-only things, or do i separate it into 2 different scripts?
Hi all, a bit of a broad question on security etc. I've heard people discouraging from using Public or [SerializeField] due to "security concerns",
my question is if I want to see variables like "CurrentHealth" in the inspector (without using debug mode), SerializeField would be an easy way to achieve that.
Noting that I know SerilizeField make fields editable in inspector, but if I know I'm not touching it, what's some concerns around that?
There's no security concern. Your entire game can be presumed fully compromised as soon as it's running on a client's controlled machine.
For displaying non-serialized fields in the editor for debugging purposes, you can use something like Naughty Attributes' [ReadOnly] attribute.
https://github.com/dbrizov/NaughtyAttributes?tab=readme-ov-file#readonly
Not sure about whatever "security concerns" are but you'd use the access modifiers relative to your needs.
Thanks! I'll have a look!
I think it was more so saying if I have too many public fields in my code, it will be a mess in future, thus should avoid using public fields
yes, this is really what it's about, and it might not be a problem on a smaller project but limiting the possible areas of code you know a value can be changed from helps a lot with debugging and reasoning about those values on a bigger scale
a private serialized field can only be changed by you in the inspector or by code in its own class, so you only need to look there if the value is something you don't expect
There's nothing wrong with [SerializeField].
The reason why you should not use Public depends on the context. In general you should keep your application as restrictive as possible. Therefore you should by default keep variables private or internal. If they should be edited from another class, or by a consumer, then consider using a less restrictive property, or methods. Generally you never allow public fields/properties.
As a beginner this doesn't matter as much, but if you work on a big project it becomes very messy when everything has bad restrictions and it becomes unclear what modifies a field/property
Lastly, it avoids tightly coupling everything which makes it easier to change your code.
These are valid points, you should pretty much always prefer [SerializeField] over public, if all you want is to show it in the editor. But you shouldn't be making a field serializable if all you want is to see its runtime value in the editor, even if you make sure not to touch it yourself.
FYI you can view variable values without [SerializeField] if you enable debug, or whatever it is called, in the inspector
[SerializeField] is mostly for if you also want to mutate the value from the inspector
Which they also mentioned in the question and didn't want to use.
my question is if I want to see variables like "CurrentHealth" in the inspector (without using debug mode)
Good point, I want to quickly touch on decoupling, is this a valid approach?
Main Script:
internal Stats Stats;
internal PerksManager PerksManager;
internal ArtifactsManager ArtifactsManager;
internal StatusEffects StatusEffects;
private void Start()
{
Stats = GetComponent<Stats>();
PerksManager = GetComponent<PerksManager>();
StatusEffects = GetComponent<StatusEffects>();
ArtifactsManager = GetComponent<ArtifactsManager>();
...
Technically the scripts are separated thus decoupled, and each script has one responsibility
Why are all these fields internal? They should not be
These fields are created because your script depends on components to work properly. Why would they be mutated from elsewhere? I would keep them private unless you have a reason
That said, if they do get changed because for some reason the component has changed, I would instead make a "refresh" method and have the script refetch the components
You should never rely on another script to do this for you
Sometimes for example... in the... PerksManager, it reaches via the MainScript, into Stats. That's why I have it internal
I find that I always lean towards this kind of structure where scripts kinda intertangle? Is it bad practice?
Why can't it just get the component directly then?
I don't understand why it goes through this script. If it can find this script it can also find those components
that's true, since they are all on the same obejct LOL
Exactly π
And if you get rid of this coupling it generally becomes more readable too
And now this script no longer relies on another one
technically they still do right? Since I still need it to exist to GetComponent of it
then they are just chunks of code in different holders I suppose
I mean your PerksManager no longer relies on a MainScript to fetch components from as a dependency
Technically you can still have a script to fetch from, but if your MainScript already exists for something there's no reason to couple PerksManager to it if the only reason is accessing components
Though i'd argue that's a bad idea because you just create messy abstractions
You should learn that each script has a specific purpose. You can couple them together if they need to communicate, but in this case you might want to do these through events
yea, I think it's good to not have scripts reaching into each other where they can easily GetComponent within their own script
Thanks! I'll take a closer look at the scripts haha
this is very cool as well, the extensions on attributes
why is this code unreachable?
because your if statement can never evaluate to true
wait im an idiot
why am I trying to compare the names, I can just compare the values
Did you notice the word 'Addressables'? Did you go and read the documentation about them?
Im creating a system to load assets at runtime when the game is running but i didn't find nothing about this
I would like to load a resource located on the disk like C:\Users..\Desktop
And how do you expect to do that? What kind of asset? How will you work with it in your game?
I'm creating a sandbox game and I'd like to give players the option of loading assets they've created beforehand on Unity. For example, FBX models, ScriptableObjects, maps, etc
ok, then you need to look into UnityWebRequest and you will need to use the file:/// protocol
your other option is to use Addressables but that puts more work on the users
What is the difference between those two things ?
Like pro and cons ?
Addressables is a system specifically made for this kind of stuff so, once you figure it out it 'just works'
WebRequest is generally used for getting data from the web but can be used for local files. It has many built in methods for handling different file types
I would suggest you read the docs on both
you may even need a combination of the 2 depending on the asset type
Thanks for your answer ! π
this is the full script
https://pastebin.com/E7HeUdbH
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.
are UnityWebRequest.Post broken?
Probably not. Unity devs most likely test their code before deploying a new version, like a majority of software development companies
Check out #854851968446365696 for guidelines on how to include the most relevant information in your question
Hey guys, I was wondering if anyone had a portfolio for their game programming they wouldn't mind showing me. I've recently been laid off and I'm looking to get back into the market for jobs, but I don't know what a good portfolio looks like for the field. If anyone can, that'd be really helpful, thank you
I'd ask in #π»βunity-talk, it's not a code issue
okay, thanks
When having serialized in the inspector List of class Foo, which contains
public string bar = "default value";
is there any easy way to create an item Foo with bar set as "default value", instead of (string)default?
Why do you use TryGetComponent if you don't handle possible missing components?
This is the same as GetComponent, but it just fails later
how come when i do this it looks like the first attachment but when the video guy does it it looks like the second attachment
You have not fully configured your !ide to support syntax correction like this
that's it, but the bot seems to be slow right now
how do i fix it
It seems the bot is down, it was supposed to give a link
check #854851968446365696 for the instructions for configuring your IDE since the bot doesn't seem to be able to share the instructions right now
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
β’
Visual Studio (Installed via Unity Hub)
β’
Visual Studio (Installed manually)
β’
VS Code
β’
JetBrains Rider
β’ :question: Other/None
lol
Well, there it is @velvet zealot
i guess it likes me, im flattered
I have a problem, I am trying to use the OnMouseOver method but it is never called and I don't understand the reason.
i have a correct size of my colliders
a sprite renderer
i dont understand why it's not working
does anyone know a tutorial to help in creating an inventory and drop and pick up system to work with an animator system , need to look for a framework over how to do it as I finally got the state machine working but I need some help in implementing some sort of pick up / drop system
how did you verify its never called, also show inspector of this object
im so confused i install dotnet but when i run the cmd command dotnet --info it says it isnt installed help please
did you install the SDK or runtime
So I need to zoom into a sphere that's about... 12.7 million meters in diameter.
Any tips for doing something like this?
scale it down by 12.7 million times
half joking - but you aren't going to really be able to scale to that size unless that is your app - and it's some sort of astronomy mapping thing.. in which case you're essentially going to have to render on the fly, downloading texture assets from a server of some sort
but rendering the geometry as "best guess" for that resolution - ie, a sphere
It pretty much is the app. I have a series of locations that need to be accurately mapped across the planet. Going down to the scale of towns/neighborhoods. I understand that I obviously don't just take a sphere and scale it up and down. I'd like to know what the strategy for something like this is.
Substitute low res models for higher res models as you zoom in (you may start with a sphere but eventually end up with a plane disguising as part of the sphere - relative to location).
Could I not just take a plane and distort it the whole way?
You only see one side of the Earth at once obviously.
If the back doesn't "close" properly then it doesn't really matter.
I had assumed that you needed the original sphere (planet or whatnot)
So.. this is a data science problem that's likely not gonna get a "good" answer from an anonymous discord server, but.. my armchair architect brain says your solution is going to be to have basically a google-earth type simulation, where you have multiple levels of the view, and depending on where the camera is in the app, you render and show that view on a plane/sphere
I'm not exactly sure what your use case is - this discord tends to be for games, and if it's for a game, then your solution is likely going to be something different or hacky. In any case, you'd probably want to write your own rendering library that can stream the texture assets in from a server, preload them (async) before your camera gets there, cache them when not using them, and render placeholder textures for each texture (perhaps a tiny/pixelated version of the area that comes preloaded with the application) before the texture load and render is ready
It's a complicated problem, and .. I'm just not sure what the cross section of "someone who has access to 12.7 million meters of texture data" and "someone who doesn't have coding/unity experience or a team that does"
So there might be something I'm missing.. but.... there's your lazy (no pun intended) answer
I understand there's quite a bit of complexity with texturing such an object. Right now though I'm just concerned with positioning things correctly on this theoretical sphere, and representing the changing curvature as you zoom in and out.
For example with Google Earth. Obviously they don't have a 12.7 million meter sphere in there... probably. Do you think they swap out a sphere model for a BIG plane at some level of zoom?
Or is the whole structure dynamic?
Honestly, I don't know - it's likely they have a variety of very smart people working on this. There's probably a team for rendering and pre-rendering geometry in a way that the UX is snappy and quick. There's probably another team for getting texture data to the client on time (or ahead of time) for rendering. There's probably another team for deciding how to integrate positional data (terrain, highways, points of interest) into both of the above.
That's just not something one person is gonna be able to answer unless they're just speculating.
There are tricks to rendering "astronomical to ant" levels of zoom, but .. I don't have experience with them. I imagine it's something like rendering a sphere until you get close, and swapping it out for a plane at some point, but... the details of how to get that to work seamlessly are an application specific detail and .. your question is a bit broad as it stands. This is a general code channel for people who ask questions like "why is this line of code not working".. you're not going to get much useful/thoughtful architectural guidance for your problem, I suspect. π
Ehh I've seen some more theoretical/problem solving-esque questions hit this channel before.
Though I'll admit this is definitely out there.
so i'm working on a webgl game that crashes at some point, and then i can't check the logs in the in-game debug console, is there a way to make it print logs to a file or something so i can see what all happened before the crash?
Are there any ways to have a monobehavior function get called on project open in editor mode without labeling the script "ExecuteInEditMode"?
it probably is either a flat plane with some tricks to make it look rounded, or it is a sphere and they subdivide it into different tiles with textures on them the more you zoom.
thanks a lot for the super thorough response! you have given me a lot to think about.
for some reason I am drawn towards a component based architecture because i have already sort of gone down that path, and mixing interfaces with components will just result in me having a dirtyer architecture (I think?)
but I will need to think about it a bit more. thanks again!
i would recommend implementing a latitude and longitude coordinates system for such a task
something like this (please look past my terrible drawing skills π )
you could techinally do this by placing small dots all around said sphere acting like coordinates
and only draw the ones the camera can see
or you can literally make a geographic coordinate system if you want
I was wondering, what is way to tell if my dll is executed by unity engine? I want #if UNITY_ENGINE class UnityScript : MonoBehaviour{ } #endif and #if GODOT class GodotScript : Node2D{ } #endif. I want this conditional compilation because a lot of code is the same and I want to be forced to copy paste code which is common and engine independent (I have probably written about this on this server). Is there a simple way to have UNITY define? I just see a bunch of UNITY_STANDALONE_WIN, UNITY_STANDALONE_LINUX, ENABLE_MONO, ENABLE_IL2CPP, ...
You can define your own keyword in the project settings and use that.
Ye, might wanna skip the interfaces in this case. np, gl hf
there is no simmple UNITY symbol which is leaving me with 2 solutions: 1) #if UNITY_2019 || UNITY_2020 || ... define UNITY .... #if UNITY but this way is error prone cause unity may decide to introduce another symbol and customers playing my unity game from other environments have unity but none of "UNITY_2019 || UNITY_2020 || ... " symbols are defined at their end is defined and it won't work. 2) is what you said: every unity project should define UNITY symbol in order to be able to use those conditional #if UNITY ... #endif functionoalities. This is better solution because every customer will have UNITY symbol defined. Thanks!
Hi all, when using an oberserver pattern:
internal event Action<int, Transform> OnAttackDealt;
private void Start()
{
_battleManager.player.OnAttackDealt += HandleDamageDealt;
}
Is the best practice to also pair this with a :
private void OnDisable()
{
_battleManager.player.OnAttackDealt -= HandleDamageDealt;
}
Something like this? If so, may I ask why? Is it due to subscription carries over from scene to scene etc?
Just one note though: typically engine independent code would be in a plain C# class. Then you can just make a wrapper for each specific engine.
Yes, but Start pairs with OnDestroy. OnEnable pairs with OnDisable.
now hyperthetically if I don't... what could be the issue?
since a script is already disabled/destroyed, they won't trigger anything
As for the reasoning is so that destroyed or disabled objects don't respond to the events.
Forgetting to unsubscribe is an often cause of null reference errors or "referenced object is destroyed" kind of errors
They would.
the way Im thinking about it, the listener are the ones "reacting" to an event, then if a listener is destroyed, they won't "react" to the event
but I guess that's why I asked hahahaha
It's not the script that invokes the subscribed method, but whoever invokes the event.
good to know, thanks!!
You can think of it as an invoker having a list of all the subscribers and calling their methods in order.
so a rule of thumb is when ever I += to an event, I'll make sure I always -=
but technically the invoker should not have visibility/should not care about what subscribers there is
Yes. There are some exceptions, like objects that don't get destroyed at all or are destroyed together with the invoking object, but you wouldn't lose anything by unsubscribing those as well.
It doesn't. The event object(Action in this case) has.
Sorry I think I didn't understand what you mean?
Don't inherit MonoBehaviour in scripts that are supposed to be shared between engines.
Instead have them as plain classes and then have an engine specific wrappers that call your engine agnostic code.
yes you are right
A bit on an extension from this question:
I'm making an autobattler, now the core mechanics are in place between scripts, the game is playing with zero graphics. I just need to implement the graphics, are observer patterns a good way of dealing with the animation sequences? It seems like a logical approach.
Yeah, sounds fine.
Hahah thanks, just need someone to validate on the approach before actually doing it
how does this work? not being on a gameobject or anything
does it create a gameobject just to run the function? or is running w/o needing a gameobject at all
i tried to figure it outmyself by logging this. but.. ofc that doesn't work
there is no gameobject involved with this
if the confusion is coming from the inheritance of MonoBehaviour, that has no effect on this static method and really only affects unity messages like Awake, Start, Update, etc (and of course provides inherited members that will only be correctly assigned if the component is correctly added to a gameobject). This static method does not require any of that and is just like any other static method where there is no object reference involved in its invocation
ohh okay thanks π
yea thats what i wasnt understanding
I need help making a script
Right click in the assets folder -> create new script.
No need to thank me.π
I mean making a script that triggers animation
Follow the previous steps, then write the code. Done
But seriously, if you need help you should provide a bit more info
Check !readme on how to ask questions
I don't know how to write the script
What do you have so far? What part are you struggling with?
If you're a total beginner, you should be asking in #π»βcode-beginner
https://www.youtube.com/watch?v=hkaysu1Z-N8
here you go
Letβs animate our character!
β Check out Skillshare: https://skl.sh/brackeys8
β Watch Player Movement: https://youtu.be/dwcT-Dch0bA
β Download the Project: https://bit.ly/2KK5AG8
β Character Controller: https://bit.ly/2MQAkmu
β Get the 2D Sprites: https://bit.ly/2KOkwjt
β€οΈ Donate: https://www.paypal.com/donate/?hosted_button_id=VCMM2PLRRX8GU...
!learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
OnTriggerEnter()
damn, 8months after i joined the team, i finally knew how the hell they loaded the resources
hey i get this error when i open VS code with a c# script and (i have no syntax overlayfor unity which is my problem) i have installed the sdks and it stil hasnt fixed any ideas?
it is something do do with the users on my pc as when i do cd C:\Program Files\dotnet then try any commands in cmd it works
but if i dont it says a similar error as vs code
have you restarted your computer
just to clarify in cmd if i just do the dotnet command it appears to have no errors but when i check for sdks using a command such as dotnet --info it says no sdks are found
i have i can try again though
i have changed a few things since then i think
(C:\Users\mawga>dotnet --info
It was not possible to find any installed .NET Core SDKs
Did you mean to run .NET Core SDK commands? Install a .NET Core SDK from:
https://aka.ms/dotnet-download) ----------------- this is the error i get
now if i run the same command that being (dotnet --info) but before this i enter cd C:\Program Files\dotnet then it works please someone help
sounds like it isn't in the Path. which means either you have not restarted the computer or it is unable to write to the environment variable for whatever reason so you'll need to add it manually
yeah i thought the same so i added it manually through windows enviroment variables and it still doesnt work
its something like i have installed any actual .net core sdks to the users\mawga but i have installed dotnet - notsure how that has happened or how i can modify dotnet to install to the correct place
if you go into C:\Program Files\dotnet\sdk do you actually see any SDKs listed there?
yes but i think its more to do with if i go to the user directory that there will not be any SDKs there
then if it isn't being detected even with the dotnet command then something is very wrong. this is beyond the scope of this server though, perhaps you could get more help in the !cs server
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
okay i managed to fix it so when ido dotnet --info in cmd it now works but it still comes up with this error in VS code
this is so weird
okay i now know what i need to do but dont know how ill figure it out
oh my god i have fixed it after 6 hours
that is the dumbest thing ever
Really struggling with the "new" input system in unity (i know its super old by now but this is my first time using it). Right now, I'm trying to add some logic to see if a key was pressed down. I have an InputAction of type Button for jumping (bound to space key for now) with the behavior as SendMessages. Here is my code:
When I press space, the OnJump() is being called but the "jump action pressed" is not. Is there something I'm doing wrong here?
you're not enabling the action
however you do not need to use both the manual instantiation of the PlayerControls class and the PlayerInput. choose one or the other
Gotcha, so what are the benefits of using either approach?
This worked, ty π
you get more granular control over which actions are enabled and can subscribe to the c# events directly using the manual way. the PlayerInput component abstracts a lot of it for you so it's "easier". see the documentation pinned in #π±οΈβinput-system to learn about the different ways to use it
Ahhh didn't realize there was a whole channel dedicated to this. Thanks π
chances are your input-system-related questions are better off asked here still, as this channel is way more popular π
that aside, a quick search in: input-system can be fruitful
So, we're better off asking all unity-related questions in #archived-code-general, as it's more popular
If you have an advanced question there are people dedicated specifically to #archived-code-advanced that are more likely to help on a hard/advanced issue.
And #π»βcode-beginner lets helpers know theyβre helping someone possibly not familiar with topics other than the one theyβre referring to, etc.
And #π±οΈβinput-system was created for questions about the input system to separate them from the general ones
and the same logic is used when people ask about why their animations dont work. the channels are made for a reason
use common sense, lol. Programmers might be unlikely to know about animations -- but the usual crew of domain-specific channels will know more
i would also call it common sense not to suggest something that the server tries to heavily enforce, meaning post things where they belong.
common sense? On this server? That would be refreshing
specifically #π±οΈβinput-system has 2-3 usuals including @knotty sun which apparently wants to chip in xD
Hi, I'm trying to make a mario kart item system for my racing game in unity. Right now, it's structured so each item is a scriptable object that holds tags which dictate what type of item it is (eg: boost, projectile). The problem is that the item doesn't store any parameters inside it, that's done on the player object, which makes adding new items really difficult and makes the item handler script long and confusing. Is there any way to move the parameters for each item onto the scriptable object? Each item will have different parameters (eg: boost might have boost duration and strength, projectile items will have the gameobject to spawn) and i'm not sure how to structure it
I'm not sure I understand what is stoppi ng the parameters from being stored on the item SO
Because each item is from a generic item SO i cant have different parameters on each of them right now
sounds like you need to restructure it to do so
you mentioned you already have a tag system
it's common for the tags to have values associated with them
Maybe a tag is like:
public class Tag {
public string name;
public float value;
}```
then you can have a tag that is (Boost: 40)
for example
Yeah it's exactly that
The problem is i need other things on the tags like gameobjects
Depends on the item
For a projectile item it needs to have the projectile it'll spawn for example
you can put an enum in there to see if its the correct item
ok then...
public class Tag {
public string name;
public float value;
public GameObject gameObjectValue;
}```
Is that not confusing though, because then i'll end up with loads of empty parameters on the tag scripts
That are different for each item and have generic names
then use an enum
then if you know what the item is why do you need the gameobject
Because each item needs different parameters
you said you already know what the item is, so why not adjust the parameters in the SO?
the gameobject seems irrelevant then
if you already know its a projectile item then use projectile parameters
It's a pretty standard technique, not really that confusing. The code that cares about a particular tag will know what kind of value it should have
Yeah you're right, I am overcomplicating it a bit
Other code won't ever see or touch it
https://paste.myst.rs/5tcw4u4l
So I have this code for an NPC, and when you interact with them they start speaking, and I have a coroutine that displays each individual letter after two frames instead of all the dialogue just being displayed at once. However if the player presses the interact button again it just skips the sentence and goes to the next one. How could I make it so that if the player presses the interact button while the coroutine is running, it just displays the rest of the text, and only then if the player presses the interact button again will it go to the next sentence (or end the dialogue)?
a powerful website for storing and sharing text and code snippets. completely free and open source.
im new to unity and i opened up visual studio to this
does anyone know how to fix this?
Right Click the project (Assembly-CSharp) and select Reload with Dependencies
But itβs a good practice to always follow the βGetting Startedβ guide of any new thing you get into, including Unity
this one is literally 2 minute read: https://unity.com/learn/get-started
but I would sugest the whole thing here: https://docs.unity3d.com/Manual/UnityManual.html & https://docs.unity3d.com/Manual/UnityOverview.html
tysm dude ur a star
Ignore me I was just too lazy to figure it out myself
Yep I read your question and was like... "surely they can figure that out"
It's better that I actually try and do it myself before asking on here so that I learn
I used to never have a problem with this but now whenever I try to use Random it gives me an error about it being ambiguous and I need to specify using Random = UnityEngine.Random; just to be able to use it. Is this normal behavior?
yes
ah, I guess I never noticed or don't remember
if two used namespaces have the same class name, how is it supposed to know which one to use
magic :(
calculators don't work on magic xD
If you have using System yes
It is because it is mixing up System.Random and Unity.Random
So I have an interface called IAsset, then I have an interference IOutputAsset<T> where T is any class that implements IAsset. Then i have a concrete type TextureAsset that implements IAsset, and TextureOutput that implements IOutputAsset<TextureAsset>. Having an object of TextureAsset referenced by IAsset, through reflection (i guess) how can i get the type TextureOutput?
Why do you need a separate class / interface for texture output?
for getting the type canβt you just do type GetType() => typeof(T)?
Get it from where? Could you not just try casting to this type
I had a question too if I'm not interrupting atm
!ask
You can just ask. The last message was 30 minutes ago..
: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
!ask
If I wanted to make a game like Asuras Wrath or Detroit Become Human with pretty much just quicktime events with an animated story, where would I even begin in terms of code? My main problem is trying to figure out how to not only systematically create prompts and gauge accuracy from them, but also whether using/switching between already rendered 2D videos would be better than creating 3D animations and animation clips and designing the entire world with said events.
: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
Timeline is a good system for creating the cutscene style animations.
You can have a scriptable object for all the cutscenes storing the timelines, and then maybe a derived one for cutscenes with quick time event prompts
And this is using the 2D video approach? That way I could flesh out the animations all in blender and then port them to the time line?
Donβt use timeline if you want to do that. Instead just use the video player.
Timeline is for rendering in real time.
OK I understand. I may try the timeline approach instead. After trying the video player and switching between clips it gave a few jittery transitions and didn't feel as fluid.
You probably should
Less storage
Alrighty! Thank you so much!
Np
is there a way to persist nativearray data between assembly reloads, without going through unity's serializer?
One is a scriptable Object that holds the data itself, the other is a graph node that has the responsability of handling inputs and outputs
I can't because that would give me the type of the IAsset but not a type of IOutputAsset
The idea is to not have concrete names of types so that I can create other types implementing the same interfaces and still work
It's not really clear what you're actually trying to do. I ask from where because it doesnt seem like anything references the TextureOutput so I'm not sure what you're trying to get. Or why it needs to be gotten in the first place
Ah okay
i don't know if the memory used by the persistent allocator is safe to keep using between domain reloads but i guess if it is, you just need to store the pointer somewhere and reconstruct the array from it after the reload, this sounds like some fun evil science to try
So I made a graph view. This graph view needs a type to instantiate nodes. TextureOutput is one kind of type that is a node. The system until now allowed to generate nodes by a menu and selecting the type of node that you want.
Now I would like to add a drag and drop system. From the inspector I have Texture Asset Scriptable Objects that could be inserted into a TextureOutput node and do their thing. However I would like to add the functionality of dragging and dropping this asset into the graph and automatically generate the corresponding node with the corresponding texture asset selected.
This system should also work with other assets that have a corresponding node that's why I'm relying on the interfaces that define it. Another example of an asset is a vegetation asset.
Both implement IAsset and both have a class that implement IOutputAsset<The asset> (aka IOutputAsset<TextureAsset> and IOutputAsset<VegetationAsset>).
So the idea is that, from the dragged object that implements IAsset, find the first concrete type that implements IOutputAsset to spawn the corresponding node.
I would guess I would get yelled at for leaking memory, and the new problem is now to figure out how to suppress unity's yelling lol
oh boy, number of leaks
you could maybe just allocate the memory yourself and convert it into a NativeArray with no allocator set as needed, that way unity won't care about what you do with it
oh right, like, within an unsafe block?
i don't think it's an actual unsafe call, despite the name: https://docs.unity3d.com/ScriptReference/Unity.Collections.LowLevel.Unsafe.NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray.html
You are sure you can't generate the data after assembly reload again?
I totally can
Then I would say subscribe to before asembly reload to dispose, and after assembly reload to regenerate it
yeah, that's my current implementation
I was mostly wondering if there's a way to keep the data, without going through a potentially slow serialization/deserialization step or recalculating it all
for example, I might have to make my own undo system, because unity's undo diff/serialization/deserialization was getting real bad for the amount of data I use
and so I'll probably manage my own stack of undo states, and keeping that without unloading/reloading it would be neat!
I see!
I found myself in a similar place a while ago
And honestly, I just kept everything organized and worked with Unity as much as possible to avoid reinventing the wheel. There were a couple of workarounds but it ended up working. But I was probably not using so much data. (not sure how much are we talking about here)
working with unity to not reinvent the wheel is my usual approach too! but, rn I'm having to refactor bc unity's wheels are caving under the pressure ahah
There is one way, which I've used with great success, to handle this situation.
Create a console program which handles the data and is started by Unity, then use named pipes between Unity and the ConsoleApp to access it
hmm, I don't think I'd have to go that far to do it, I should try the manual allocation thing first!
(also that has lots of implications for the asset store and multiplatform dev. I'm making a plugin!)
For reference, this is what ended up working!
var nodeType = TypeCache.GetTypesDerivedFrom<InfiniteLandsNode>().FirstOrDefault(a =>
a.GetInterfaces().Any(i =>
i.IsGenericType &&
i.GetGenericTypeDefinition() == typeof(IOutputAsset<>) &&
i.GetGenericArguments().First().IsAssignableFrom(asset.GetType())));
Here InfiniteLandsNode is the base clas of all nodes
Ah sorry I got busy I was gonna suggest going through the derived types to compare. But wouldnt you need to compare if its IOutputAsset<IAsset>? Where IAsset is the class implementing it
I dont use reflection all that much myself, so I'd probably just manually define the type in each IAsset definition
it's cool hahaha. The problem is that I don't have the class that implemetns IAsset as a generic to type there but as a type variable
Like, it comes like this
public void OnAssetDropped(IAsset asset, Vector2 position){
var nodeType = TypeCache.GetTypesDerivedFrom<InfiniteLandsNode>().FirstOrDefault(a =>
a.GetInterfaces().Any(i =>
i.IsGenericType &&
i.GetGenericTypeDefinition() == typeof(IOutputAsset<>) &&
i.GetGenericArguments().First().IsAssignableFrom(asset.GetType())));
....
And this is not allowed typeof(IOutputAsset<asset.GetType()>) &&
I just had a thought, unsafe code is not allowed in assets for the asset store
oh what really? ;-;
yep, read the submission guidelines
hmmm are you reading this?
bc this honestly seems vague enough to potentially not refer to the unsafe{} blocks specifically
since it's a sentence about safety/harmful code
up to you if you want to risk it
I'll just ask unity
cya in a couple of months!
Just curious, could you use this to compare the type?
https://learn.microsoft.com/en-us/dotnet/api/system.type.makegenerictype?view=net-8.0
To assign a type to that generic in IOutputAsset
mMM, so If I have an interface IAsset, a secondary that is IOutputAsset<TextureAsset> where TextureAsset implements IAsset, I cannot cast IoutputAsset<TextureAsset> to IOutputAsset<IAsset>?
mmm let me check
It says it doesn't exist
Ah no but that would just create a type, but not actually be usable like that
It seems i stumbled upon the covariance stuff
Its just to compare if the type is IOutputAsset<TextureAsset> after getting the type from IAsset. If you want to create an instance through reflection itd be through CreateInstance likely
Hey, losing my mind trying to figure out why this isnt working. Anyone mind giving me a hand?
The target system works properly minus the camera on the x axis. The camera jumps back to where the mouseX position was. Its like its remembering it so i created a lastCameraRotation Quaternion to store the values but its still not updating as it should. Im simply trying to make it where it doesnt jump and it just continues but not locked in]
May have misread it but it looks like you are scanning the raycast to check for a valid target when it is already locked on
Yeah thatβs the problem
Hi, I made an IK solver that requires me to set joint rotations twice. This is stable and probably not a performance issue for me at this point, but I would like to understand how to set these rotations once per joint. I tried updating the quaternions like this, but the ik became unstable: quaternion rotationA = math.mul(quaternion.LookRotation(normalizedBaseLine, poleVector), quaternion.AxisAngle(joint0.right, -angleA + offsetA)); (working implementation in the image)
Rotate joints just once
how so?
Well your running the method that raycasts it
As its supposed to, the raycast isnt the issue
the raycast is always supposed to be running
and searching
Thatβs the reason why it is getting unlock though
Because the length of the raycast is also what determines the enemy in range to target
The issue isnt its getting unlocked though
I manually do that
I have it set in the script to manually and automatically do that after you get a certain distance away from the target.
The issue im having is the camera jumps
it shows in the video
https://docs.unity3d.com/Packages/com.unity.2d.spriteshape@8.0/api/UnityEngine.U2D.Spline.html Anyone know if it's possible to get a point X distance along a spline?
ideally with that point's tangent vector as well?
Likely this line.
playerBody.rotation = Quaternion.Slerp(playerBody.rotation, playerBodyRotation, Time.deltaTime * rotationSpeed);
playerbody rotation is good, the camera rotation is the issue. There two different gameobjects in this sense
Feeding something into itself for interpolation math can get fucky
True that, but in this instance it works. So I'm keeping it at the moment, the camera rotation stuff is my main issue
Wait,
Nvm. It is because you are not interpolating this
transform.Rotate(lastCameraRotation.x, lastCameraRotation.y, lastCameraRotation.z);
Could you explain how that would be the issue. Not saying youre wrong, but my brain understanding
Instead of interpolating the position you are assigning it
how would I go about it the other way? I tried transform.rotation but I cannot set that equal to something to change it. Unity has an error when trying to
Hello, im just getting started with splines in unity, is there a way to join two splines through code?
Just interpolate the value
yo so i just installed this datamoshing script i found on github and i installed it with the unity package which i think is the right way, though when i apply the script to the object i wanna datamosh and click the "glitch!" button it doesnt do anything, is it beacuse its 8 years old and the script is outdated or am i doing something wrong? https://github.com/keijiro/KinoDatamosh (buttons are grey in image only beacuse im not in play mode)
i would recommend asking the owner of said github page
i dont know how to
and the most recent contribution was 3 years ago so im not sure if they are still active
the github requires motion vectors which require RenderTextureFormat.RGHalf which your computer needs to support (specifically the graphics card) in order for it to work
so basically its beacuse my GPU isnt supported then?
well look up if your gpu does support it
cant find anything talking about it
it just tells me to use a component in c# but i dont know how to even print a message to console in c#
This kind of experimental asset would require some degree of expertise in unity and graphics programming from a user. Especially if you need to debug why it's not working.
So, perhaps pause your current project a bit and start with proper !learning
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
man i dont wanna go on another side quest and learn a whole new skill i just wanna add a cool funky thing to my cool funky vrchat avatar
you can use this to check if your graphics card supports it or not public static bool SupportsRenderTextureFormat(RenderTextureFormat format);
returns true if it does
yea thats what i said but i dont know how to use that
you just paste it into a script in unity
thats it
Are there any reliable methods for getting the closest Component of a type to a GameObject? I've been looking around for a good method for this but nothing seems quite right.
Get all by type, then select the one with the lowest distance
Hmm π€
Any specific recommendation for checking distance? I preferably want to keep it fairly performant
You can use the square magnitude of the point difference (skips the square root)
sqrMagnitude seems like the way to go, thank you!
Also seems like the most performant
You can also use manhattan distance but thatβs typically not what youβd want
well not a blank script lmao
i mean a new unity script that has a monobehaviour and such
you should really just go learn the basics of c# first if you expect to get anything done in unity
im not tryna make a game rn im just tryna add a cool effect to my vrchat avatar
Should probably have mentioned that earlier.
There's no guarantee that's gonna work in VR chat. I'm not sure what's their policy on including shaders and modifying the rendering loop in their avatars.
Which is what that asset does.
they have pretty much no policy on avatars
its pretty much free reign for PC avatars
It's not as much about policy as to how they are implemented
how so
Well, it's not a simple modification of adding a custom model. It's a pretty complex asset.
well ive never seen a shader working in unity that doesnt work in vrchat
Everyone that would need to see that effect would have to have these asset imported on their client.
yea
ive played with screenspace shaders which are perfectly fine in vrchat if that helps
you will need to use a actual unity script to do so
wdym
and dilch brings up a great point about modifying rendering in vrchat
you need to make C# use unity, so you need unity
I see. In this case that might work. But you still have the issue of getting the asset to work in the first place.
this is the other variation i tried
yea once i get it to work itl be fine
this is a unity script
what did this say
sure is
well what did it say then
why did you copy the signature of some method and paste it inside the Start method?
also get your !IDE configured
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
that method was in the docs to check if his graphics card supports a certain rendertextureformat
as seen here
okay but that's not how you use the method so i'm trying to figure out why they've just copy/pasted its signature into Start()
beacuse i know jack shit about C# ok?
then start with the beginner courses pinned in #π»βcode-beginner
ive said this already
i dont want to learn C# i just want to get this to work and be done with ti
im not about to go on a sidequest
you don't want to learn c#, you just want someone to spoon feed you the answer to your problem. well good luck with that
yes pretty much
Maybe try asking in the vr chat community then. We prefer to help people learn to solve issues instead of just providing them a ready to go solution.
well people in the vrchat community are mostly 3d moddelers who dont do this stuff
you lot actually know what tf you doing
+they mostly stay away from anything that was made SPECIFICALLY for vrchat
modding help isnt allowed in this server, and really you'll get more related help there. still though what you're doing isnt gonna work
Then wait for someone kind enough to spoon feed you.
You can also try hiring someone to give you a working solution on a freelancing platform, like Upwork.
why does this server mute the question mark
i never said anything related to modelers. This is essentially a mod for vrchat
Hello, is Boolean Tool in ProBuilder Plugin available to use through C# script?
and? call it what u want but its modding lmao
that doesn't mean modding discussions are permitted here. vr chat has it's own server and modding community people can get help in
oml why is this like a whole thing can you just like tell me how to fix my problem? π
It's explained in the #854851968446365696
bet
look nobody wants to spoon feed you but i will help you out with your problem
just give me a minute
ok thank you
i dont mind being taught why it is how it is
im just not about to go on a whole tangent learning the entirety of C# for 1 little problem
That being said, your GPU likely supports that feature, so I don't think that's the cause. And with debugging the asset we really can't help you, as that would involve a lot of time and effort. You'll need to hire someone to do that for you.
Or learn it yourself.
man the people in the shader discord were alot more forgiving like i said my problem when i was doing something and some guy just showed up like "here is the fully written shader with 5 extra features cuz why not" π
https://github.com/Unity-Technologies/com.unity.probuilder/blob/master/Editor/EditorCore/BooleanEditor.cs#L362
i think this is the method you're looking for? are you doing this at runtime?
when i used this tool it would sometimes crash unity last year. Not sure if its still experimental or not
oh my bad this looks to be editor only
Hey guys, is there something like ProBuilder that i can use during runtime? I basicly need to make shapes mainly cubes and archs of varying sizes (i dont want to use transform scales as it makes the textures uv stretch
I am doing my project in runtime. Sadly, i would have to depend on it. i heard and saw couple of reports about it getting bugged
oh wow im not the only one asking ProBuilder quesitons right now
came at the right time
well it depends on his GPU, not sure when a GPU doesnt support it
emm i'm actually did that in my project
its an AMD GPU and i have heard AMD is pretty shit compared to nvidia in terms of support for things
but i made a 'tool' in runtime for scaling up objects
Probably any PC GPU that was produced in the last 10 years supports it. Mobile platforms are questionable.
like 1 time i tried to do some things with AI and i just couldnt cuz i had AMD GPU
@queen saffron i did my own code the cube, mesh code was easy, but i also need the arch. you want to share how you were able to do it? using probuilder shapes? i might want to set other properties, but size is my only ask right now
well my GPU was made in the past 10 years so yea idk
what gpu do you have
ah well sorry im not familiar much with probuilder at runtime. this is all the mesh operations they have though if you find what you need
https://github.com/Unity-Technologies/com.unity.probuilder/tree/master/Runtime/MeshOperations
I also believe, they'd had some kind of error thrown on shader compilation or at runtime if the format wasn't supported.
if (shapeType == Shape3DType.Cube)
{
pbMesh = ShapeGenerator.CreateShape(ShapeType.Cube, PivotLocation.FirstCorner);
}
else if (shapeType == Shape3DType.Arch)
{
pbMesh = ShapeGenerator.CreateShape(ShapeType.Arch, PivotLocation.FirstCorner);
}
pbMesh is of a type ProBuilderMesh
if thats the case then they would 110% have to learn how to use unity to fix this issue
or contact the owner of the github
i know how to use unity i just dont know C#
@winged magnet if you need more clarification, head for DM
!code
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To 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.
then go learn some C# and !learn some unity courses to use unity properly
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
And C# is a big part of using unity.
if you dont want to do this then look somewhere else in terms of this package
ok last link lol but i think this is the one
https://github.com/Unity-Technologies/com.unity.probuilder/blob/master/External/CSG/CSG.cs
doesnt seem to be editor only
wiat what i thought you said you would help me how your just saying what the other guys said π
well i was gonna help you via graphics card support
but we got that figured out
wait did we
i think it is external or another plugin ain't it?
i thought it was only probable that i had support
well if you have a fairly new graphics card you should have this feature
can you remove something from a list if they leave Physics.OverlapSphere
or can you only add?
if they leave OverlapSphere
ah, honestly i got no clue
i have a RX 5700 XT, is that new enough?
you might be able to just take the code from the github if applicable and use the parts you need
yes
alr bet now atleast i have no clue what the problem is again lmao
aight, thanks dude for the assistance?
check the issues section on the github page to see if your issue is there
and see how to set it up (if there are any tutorials)
I have a problem related to UI Toolkit and i don't know how to solve it π©
All works fine when i run my scene from the editor, but i don't have the same render when i run my game from a build
- Some parts of my UI is loaded from
Resources - The cube lost its texture when i run a game build
- UI Is completly different between the game build and the editor
Anyone already have this problem before and know how to solve it ?
(I use AppUI framework)
How do you create the cube? Does the cube use a custom shader? If so, make sure to reference it in [Project Settings]'s Graphics tab.
I don't know about UI Toolkit specifically, but seems you're either not using a layout or it's set up wrong anyway. Try using fixed height for the rows.
all and all show code or people here won't be able to help. if your framework doesn't use code, #π§°βui-toolkit might be of more use
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class DepositFilament : MonoBehaviour
{
[SerializeField] LineRenderer lineRenderer;
[SerializeField] GameObject Deposition;
const float newLineThreshold = 0.5f;
private void Start()
{
lineRenderer = Instantiate(Deposition, transform).GetComponent<LineRenderer>();
}
void ClearLine()
{
//lineRenderer.SetPositions(new Vector3[] {});
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyUp(KeyCode.Space))
{
lineRenderer = Instantiate(Deposition, transform).GetComponent<LineRenderer>();
}
if (Input.GetKey(KeyCode.Space))
{
Draw();
}
if (Input.GetKey(KeyCode.C)) ClearLine();
}
bool DistanceLessThan(Vector3 a, Vector3 b, float distance)
{
return Mathf.Abs((a - b).magnitude) < distance;
}
void Draw()
{
if (lineRenderer.positionCount > 0)
{
if (DistanceLessThan(transform.position, lineRenderer.GetPosition(lineRenderer.positionCount - 1), lineRenderer.widthCurve.Evaluate(0))) return;
}
lineRenderer.positionCount++;
lineRenderer.SetPosition(lineRenderer.positionCount - 1, transform.position);
}
}
why does this code alway add the point to the last LineRenderer also even though there should be no reference left?
anyone know how to detect "ok" "done" or just keyboard closing on android?
What do you mean by no reference left? And what's the last line renderer?
The Code draws by adding points to a line renderer. As soon as the user stops drawing a new line renderer is instantiated and the old reference gets replaced by that one so that when the user starts drawing again, the two drawn lines exist independently. But for some reason when the user starts drawing again, the first point gets added to the last used line renderer even though it is not referenced anymore.
Place some logs and see what's occurring. From just code alone, we're going to assume that while space is held you're calling the draw function and when space is released you're instantiating a new line.
What does "stop drawing" refers to?
Releasing Space
Try placing logs in both if statements and show the console
okay, got an interesting one:
I'm developing a VR game, and that game involves a digital camera that the player can take photos of things with.
Now, I'm already detecting if objects are within that camera's frustum, but I'd also like to be more specific, and have a circular area within the center of the digital camera's display, where certain objects have to be within that particular "crosshair" to be captured correctly (basically, to make sure that they are closer to the center of the camera, but not specifically requiring being dead center, which rules out a raycast.)
How do I detect if this circular area on the camera's UI is overlapping a gameobject?
what's wrong with a spherecast?
Hey just wondering how do I get rid of this?
Uncheck Collapse at the top left corner of the Console
oh thanks now i feel stupid lmfao
other than my not knowing this existed until now... nothing, apparently
If i have a character, wich when arrived at a certain point (A chair), i would like the character to "teleport" to the sittingpoint wich is a childobject of my chair, so it looks like the character is sitting on the chiar. But i can't get it to work. At the moment, the character just gets to the chair and "sits" so the animation and all works. But how can i get the character to Get its Transform.position upon the sittingPoints transform.position?
Always a good plan to check the docs if you find an API which doesn't suit your purpose, there is generally an alternative that will
unless i'm missing something
character.transform.position = sittingPoint.transform.position
Haha, dont tell me it's that easy!? Im over here trying to make it overly complex....
it's that easy.
Hah! It wasen't that easy, well, the character now sits "kinda" on that point, but since the chair is a bit higher up, the character is "stuck" on the ground in a sitting motion. The chracter got a rigidbody (Kinematic) and a nav mesh agent. What could make it so the char is unable to "leave the ground" so to say?
add an offset relative to seat height
you obviously need your sittingpoint to be exactly where the character should be
also disable the rigidbody and stop the agent
So it could be the rigidbody that screws it up, eventough its kinematic and not using gravity?
Im sorry, i might have been a bit preserved with the information in my first post.
no, missed that kinematic is OK
you could also use rigidbody.meveposition to make the transition, also maybe lerp it to make it a smooth transition
Cheers!
i have a question about Unity Editor Functionality.
if i have a array of Classes
public DataCollectionClass[] Dcc;
and DataCollectionClass contains a Constructor that needs a float input at construction, is it possible to set up the editor to input it depending on what information the current holder of the Array has?
public class SuperClass : MonoBehaviour
{
[SerializeField] private float variablefloat;
public DataCollectionClass[] Dcc;
}
public class DataCollectionClass
{
float targetFloat;
public DataCollectionClass(float floatInput)
{
targetFloat = floatInput;
}
}
i want the editor to use the variableFloat in the class when creating new DataCollectionClass objects in the array.
is this possible with a simple solution or is it very complicated?
Well, few things. For one you need to serialize the DataCollectClass to insert it on the inspector, and doing so basically gives up the constructor, basically invoking the default constructor instead, so if you want to do some type of initializer on this plain c# class you need to directly call some custom init() method
public class SuperClass : MonoBehaviour
{
[SerializeField] private float variablefloat;
public DataCollectionClass[] Dcc;
public Start()
{
foreach(DataCollectionClass data in Dcc)
{
data.Init(variablefloat);
}
}
}
[Serializable]
public class DataCollectionClass
{
float targetFloat;
public Init(float floatInput)
{
targetFloat = floatInput;
}
}```
Not the greatest example as you can probably just insert the data directly into the serialized class, but gives an idea what you need to do to get around the constructor issue.
yeah this could work for what i want to do. otherwise i guess editor extensions should be the route to go?
you can do a lot without* custom editor stuff with some extra logic. Unless you need to say serialize generics/interfaces
dealing with that now and want to die π
mackysoft's serialize references extension does solve a lot of those problems ;p
i have seen a thing or two on the internet about unity 2023 being a lot better about serializing generics?
serialize reference support has been around for a while, but you do need to make a custom editor script to get it working
i want fields to work π
if I'm working with generics I try to have explicit constraints if possible
i do but i think its getting weird cuz its like two generics deep
ValueSetting
ValueSetting<T> : ValueSetting
ValueSetting<M> : ValueSetting<Enum> where M : Enum
Yeah, Enum is too ambiguous unfortunately
is that the actual problem there?
i had one with UnityEngine.Object aswell that was also borked
If you derive a class with a specific Enum, then you should be able to serialize it
ye i dont want that tho
Not a code question #π±βmobile
thanks
That's where serialize references come into play then
otherwise keep it as plain data and don't resolve it on the editor
The field NewScriptableAudioSetting.audioMixer has the [SerializeReference] attribute applied, but is of type IterationToolkit.ValueObjectSetting<UnityEngine.Audio.AudioMixer>, which is a generic instance type. This is not supported. You must create a non-generic subclass of your generic instance type and use that as the field type instead.
it doesnt seem to like serializereference
[CreateAssetMenu(fileName = "AudioSetting", menuName = "IterationToolkit/Settings/NewAudioSettings", order = 1)]
public class NewScriptableAudioSetting : NewScriptableSetting
{
[field: SerializeReference] public ValueObjectSetting<AudioMixer> audioMixer;
}
How to prevent tunneling for the player bullet, where the bullet just passes through an object without detecting collision
protected void FixedUpdate()
{
float distanceToMove = velocity * Time.fixedDeltaTime;
RaycastHit hit;
// Use multiple raycasts along the path to ensure collisions are detected
bool hitDetected = Physics.Raycast(transform.position, transform.forward, out hit, distanceToMove, raycastMask);
// If no hit detected, try a SweepTest for more reliable detection
if (!hitDetected)
{
if (rb.SweepTest(transform.forward, out hit, distanceToMove))
{
hitDetected = true;
}
}
// If a hit was detected by any method, process the hit
if (hitDetected)
{
OnTriggerEnter(hit.collider);
}
else
{
// Move the bullet manually to avoid relying on the physics engine for movement
transform.Translate(Vector3.forward * distanceToMove);
}
// Handle bullet lifespan
if (Time.time > lifeTimer + life)
{
gameObject.SetActive(false);
}
}
I'd look into Mackysoft's solution if you haven't.
for this specific usecase i'm not looking to use anything third party
rb does some interpolation, but have you looked into the different methods of detection?
I used raycasting, but it doesn't seem to work
but the raycast there is the solution, but usually I don't need it for rbs
actually im kidn of confused. You're using transform.translate and rigidbodies
that's not ideal scenario. Pick one or the other
I am using the rb to preform the sweep test
will make a note to do this in future. TY.
Could try looking for errors in your logs
https://docs.unity3d.com/Manual/LogFiles.html
Hi ! I am confused with the AssetDatabase.LoadAssetAtPath<T>() documentation (https://docs.unity3d.com/6000.0/Documentation/ScriptReference/AssetDatabase.LoadAssetAtPath.html). When it says "Some asset files may contain multiple objects. (such as a Maya file which may contain multiple Meshes and GameObjects)", does it mean that loading an Asset also loads its sub assets ?
For example, I have a ScriptableObject A which contains N ScriptableObject as children. If I load ScriptableObject A, are its children also loaded ?
not sure how a ScriptableObject would have children at all
Well, this is not my call, but you can add an asset to a scriptable asset using AddObjectToAsset(), so a ScriptableObject with children is doable. Maybe not the best thing, but doable.
Yes, if you do that it would load the SO with it's sub assets.
OK. Thanks. Was wondering if LoadAllAssetsAtPath() was necessary.
Hello! May I ask for all sorts of Skeleton Animation(Spine) ideas? I have hundreds of them in my scene. Main target is WebGL(for now, temporary solution for a demo). I don't have much optimization experience, so anything(guides, extension assets, repos, etc) helps!
FPS drops
So when you have a object serialized.
[System.Serializable]
public class Test{
public float VersionNumber = 0.5f;
public int ii
}
and you put a new variable in it. can you convert the old version with loading to the new version than?
that will depend on how you serialize/deserialize
with the unity serialization
then new variables will be serialized with the default value
yeah but if your games load something at the beginning of the game
Anyone use AppUI as UI Toolkit framework ? I have a problem related to Panel component and i find nothing to solve my problem :/
When i put any AppUI text based component in a Panel, the component is completly break and the texte is not displayed properly. I don't have this problem if i but my component outside a Panel component πΆ
you will get a null or is there something around it?
Did a channel exists to report package problem ?
do we have any substitute for Resources.FindObjectsOfTypeAll that can be use in Job System
You can't deal with managed objects in the job system at all so no
Thanks mate
!code
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To 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.
does anybody know the solution to a very frustrating issue of mine where my player just moves backwards by itself without any inputs? i have a sim racing wheel plugged in but the issue is still around even after i unplug it. here's the link to the code (i followed a tutorial cuz i literally just started game development so i dont really know much about anything): https://paste.myst.rs/nf5bzpzl
a powerful website for storing and sharing text and code snippets. completely free and open source.
well the first thing to do would be to add some Debug.Log statements to print the input you're getting
i.e. moveSpeedX/Y
to see if it's a problem with input or something else
could u maybe tell me what exactly i should write in the code and on what line or whatever i need to do? i really dont know anything at all
then !learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
we will help you if you are stuck but wont just give you code
its best for you to learn
I can't remember how to make the skybox lower. The first photo shows how it should be, and then in game mode it changes to the second picture. I had this figured out before, but can't remember how to
The only things that affect how the skybox appears in game is the rotation of the camera and its field of view. So either or both of those are different in game mode.
Can somebody please remind me whether **light and shadows **for built-in pipeline is supported for 2d games? My objects seem to not batch and I want to test all options to compare performance.
yup, found it. Thanks
wondering if there is any workaround for this. Maybe a second camera that renders only skybox?
Was it the field of view that was the problem?
the camera angle
Then it sounds more like you want a background texture that is fixed in screenspace. You can do this with a custom shader by sampling the texture using screen position as the UV.
alright, I'll try that, thanks
i just fixed the issue and it was the dumbest issue ever
there were 2 horizontal and vertical inputs each in the input manager and it works correctly after i deleted them
hey, theres something simple i want to implement but im not sure what would the best way to go about it because i tend to overcomplicate things
i have a really simple 2d character that can move left and right
i want to make it so that if the player hits a trigger box collider ( a booster) then it will boost to the right with double velocity
put AddForce with impulse, whats the problem?
the problem is that for the normal movement im not using force, im using normal velocity
so add it to the velocity, or make temp bool for boosting
i did that, and i added like 0.5 seconds where my speed is doubled but the problem now is that after the 0.5 seconds because im using input get axis, my velocity becomes 0 which i dont want it
i just want it to slow down until stopping
make a coroutine for boosted, or still use a bool, if you're boosting ignore the inputs messing with vel
what should i do after i finish boosting
i want to have control but if im not pressing any input i dont want it to just instantly stop
if(movementInput == Vector3.zero && rb.velocity > minAmount && boosted) // do slowdown logic with coroutine or fixedUpdate
just an idea
something like Vector3.MoveTowards or something like that
very specific question: does anyone know where i could find a code snipet of taking a 360degree picture and displaying it on a 2d UI, with a way to scroll the image?
i found ways in 3d using a sphere and a camera but it's quite ressource intensive for a thumbnail
I've been planning how I want to load a large game world seamlessly. One way I'm considering is streaming in scenes as chunks. One thing I'm curious about though is if I want a navmesh to work for all chunks as a whole, will I need to rebake it as chunks are loaded and unloaded? I worry this would be expensive, and looking at links documentation I'm not quite sure that fits the job for what I need(seamless connecting of entire edges of terrain of various heights/complexity)
Is there a way to change pivot of a sprite? Need to flip on y but it flips at the wrong pivot.
Sprite Editor. Also not a code question
https://docs.unity3d.com/Manual/sprite-editor-use.html
mb was unsure if i should ask about it here or elsewhere
typically #π»βunity-talk or #πΌοΈβ2d-tools
Okay thank you!
i'm making a tooltip system and using IPointer Enter & Exit Handler to determine when the tooltip should be shown and hidden
my problem is i don't want to close it when the cursor moves to the tooltip, so i introduced a bool isPointerOver to both the tooltip and the tooltip trigger, which fixed that, however now idk a good way to actually close them
is there a more elegant solution to this? maybe taking the cursor position and seeing if it's over a tooltip or tooltip trigger?
i'm having issues using the event system in ugui usint the input system, i got my own action asset that has all the necesary actions for the UI to work
but when i click a button that i modified so it deactivates on click
nothing happens
what could be the cause of this?
how did you "modify" it to deactivate on click
apologies, i should've said directly that the onclick event it calls to its game object's "SetActive(false)" method
Also all the normal things to check:
- Do you have an Event System in the scene?
- Does the event system have an appropriate Input Module on it?
- Do you have any other thing blocking the button?
this OnClick will set active to true
apologies, it was originally set to false
my bad
i'm a bit shooketh by stuff happening in other communities i'm in so i'm a bit rusty
Is the button highlighting at all when you mouse over it?
no, nothing happens
Then you need to check this stuff
it's one of these issues
- Event system is in
- Input module is in, specifically the InputSystem UI Input Module.
- Not that i know of, i used OnGUI methods for debug functionality but i removed all thsoe calls
Does the Button image have Raycast Target enabled?
yes
Does your Canvas have a Graphics Raycaster on it?
yes, set to ignore reversed graphics, no blocking objects, and everything as blocking mask
Try this:
- Select your Event System object so its inspector is showing
- Run the game
- Mouse over the button
See what the preview window for the event system says
it should ideally show that you moused over the button
there's a preview window for the event system?
even then
moving over the button i see no changes to the event system's fields in the inspector
nvm
you meant this praetor?
if so, hovering over the button changes nothing
...oddly enough
setting the event system's input actions back to the default fixes it and now it works?

correct me if i'm wrong but that doesnt make sense. unless i dont have the required actions. but since i do have them this just confuses me
nevertheless, using the default inpuit action works
if it means anything, the way how i added the required actions to my input action asset my game uses was by just copy pasting the ones found in the default input actions
This makes sense if your actions asset wasn't configured properly
In general there's not really a good reason to override the default input actions asset on the input module TBH
fair enough
i thought copy pasting would work but i guess it doesnt
Hey me and some people are making a unity indie game we need 1 more scripter. If anyone wants to help dm me.
!collab requests / ads are not allowed here, use the forums instead:
: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
Alright my bad