#archived-code-general
1 messages · Page 394 of 1
why are you setting it to null in the declaration? _intervals = null;
just a reflex
to set everything null until i change it
but its not null in the editor
ok so don't assign it null to begin with and try running again
bro if i dont assign anything its automatically null
and i set values in the editor
so its not null
and it works for the character
well you are going to get the null reference exception if you:
-
don't apply a null check on the instance of the class/object
-
it's set to null upon start
?? SerializeField only makes it visible in your inspector
this will have no effect
the field initializer is applied when the object gets constructed
Unity then applies serialized properties to the object
iterate over every item in the list and call PulseScale on it
Are you creating a BeatSync by adding a component to something via code?
i'm not entirely sure what his code structure looks like. what he's sharing with us seems quite vague as it seems like there are other scripts in play
I agree that this is a very confusing mess of random code, yes
I need to see all of the relevant scripts in something I can actually follow -- one paste link per script
no screenshots
I do not currently understand what you are doing, which makes it very hard to offer any advice
Is there something else other than fov that affects the camera scale? Specifically I'm asking about pip scope calculation, for example in escape from tarkov a 1x pip scope has 15 fov on the camera, which gives a similar result as a non-pip reflex scope that changes player camera fov to 55.
However if I try to replicate the same 15 fov camera setup in unity, the scale in scope is much higher than in game. Could someone please explain this to me?
!collab 👇
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
Oooo my bad
"pip scope"?
ah, proper scopes that only zoom in inside the scope
(picture-in-picture)
One important thing is that unity uses vertical FOV -- maybe Tarkov uses horizontal?
Hi, I believe it is vertical as shown in their community modding sdk project. Besides, I'm modding 7 days to die and checking the camera at runtime with unity explorer, it also says it's vertical
Here's some comparisons I took before:
as shown in the picture, the 2 cameras have the same fov but significantly different scale. I think I have copied the properties from the main camera via Camera.CopyFrom
Besides, the forum suggests that you can't change unity's fov axis so it always stay vertical.
https://discussions.unity.com/t/changing-the-fov-axis-from-vertical-to-horizental/838573/2
I'm still hoping to get some hint on what might be affecting the zoom😭
hey guys um
im not necessarily making a game
im making a library app for my school
any ideas?
Many ideas. Try eating ice cream with mustard.
how do i assign a material trough script? here is what i did already (simplified because i am using arrays of objects and materials)
MeshRenderer Renderer = Block.GetComponent<MeshRenderer>();
Renderer.materials[0] = BlockMaterial;
all of the objects end up with default materials
any idea what i did wrong, or how to troubleshoot it?
IIRC you need to set the material array itself if you are changing materials
Renderer.materials does not return the original array
oh
float avoidFloorDistance = 0.1f;
float ladderGrabDistance = 0.4f;
if (Physics.Raycast(transform.position + Vector3.up * avoidFloorDistance, targetDirection, out RaycastHit raycastHit, ladderGrabDistance)) {
Debug.Log(raycastHit.transform);
}
I have a basic raycast code in Unity, this raycast does not work if the collider of the opposite object is triggered, if not, how do I solve this problem? I am using Unity 6. I did not have such a problem in other versions.
not a " isTrigger" problem, you might be doing somethign wrong. you can debug your ray to see if it is facing the right direction
any good ways to make minigolf physics not suck? had to lock rotation on the ball because hitting walls made it spiral and fuck up the arc, but that just resulted in the ball not wanting to slide into the hole
ama post the border and ball pmats in a sec but already nuked angular drag n it fidnt help
Just tried creating array of materials and assigning it to mesh renderer, it worked
I have encountered a strange problem: if I set canvas scaler to "scale with screen size", the sliders just break when the resolution of game window is higher than roughly 1600 by 900. I can press the handle, but I can't move it with my mouse. It happens in both editor and build, maybe I am missing something?
: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
ball
border
I'm having trouble understanding your issue.
the 2 cameras have the same fov but significantly different scale
What 2 cameras? Do you mean the player cam and scope cam? Or the scope cams in your screenshots?
I guess im asking what is the real issue here/what is not working properly
I personally had to just eyeball the FOVs for PIP scopes
I mean the one in unity editor and the one at runtime, they have the same setup
Ok you didnt mention that or im blind
but as you can see, the sphere in the editor is correctly scaled while the runtime camera actually downscale the cube
Okay I see now
I'm completely clueless about what might happen in between, so any suggestion is appreciated😭
Doesn't the player camera's fov also change when you aim in 7d2d?
Is that replicated in the editor?
It actually supports zoom in and out the player camera with mousewheel, and doing that in game does not affect pip camera at all
And it shouldn't anyway
I can simulate it in editor of course, it's basically another fov change
- player camera with 85 fov
- player camera with 37 fov as the previous in game image
So the viewmodel doesnt scale with the player camera's FOV?
Because these look identical to me
How are "level up stats" usually implemented?
For example: in rpg maker, you'd have these curves where you can set the stats for each level (refer to screenshot)
Example 2: A game like pokemon or any rpg really, where each unit levels up and gets different stats (some get more atk, others more hp, etc etc).
I'm aware that I'd need to built my own system in unity. Right now I have my stats in a ScriptableObject and I'm using composition to set it in my monobehaviour.
class Unit: MonoBehavior {
[SerializeField] StatsSO stats;
public void Awake(){
//copy stats to class variables as a reset per battle
// also allows for easier time dealing with stat changes due to buffs/spells
// since the SO is treated as read-only for initialization
// and getting the "original" data
this.atk = stats.atk;
this.hp = stats.hp;
....
}
}
However, I'm not sure how to handle leveling up. Making an SO for each unit and for each level (Each unit can go from 1-9 and each unit has a different stat progression, so each should have their own formulas/curves) seems time consuming and probably not the way.
Does this mean that each SO needs to be aware of:
how much exp for the each level?
The stats/curve at each level
Then it becomes a matter of comparing my current level and experience points with the next level's?
If so, are these curves often generated using json/external scripts?
or are there some plugins people typically use? (ideally: official packages or something of the sort)
Sorry for the beginner question, I'm just confused.
@gilded crystal And are you aware if 7d2d uses a separate camera for the viewmodel (arms+gun)?
Yes, it was achieved by bliting a weapon camera render texture onto the player camera texture before, and the devs removed the weapon camera and achieved the same effect by setting some material property block for fpv renderers in the latest update, and I've also added that script to my editor project so it works the same way
How do I publicly mention MinMaxSlider or mention it at all
Btw, from the escape from tarkov modding project, the pip camera starts with 15 fov for 1x zoom and that's what worked for me in 7d2d game too
AFK real quick
Math seems dead to me
wow i love interfaces wtf i just figured out what theyre used for
Wdym exactly? This? https://docs.unity3d.com/ScriptReference/EditorGUILayout.MinMaxSlider.html
Oh no I understood it in the end
Apparently it wasn't some sort of property I could use to get from sliders (the component)
but now that I'm trying to just get sliders themselves I noticed the component sliders can't be drag and dropped as a public property
Hi, I am trying to create a class that can be serialized in json.
It's working well so far, with one exception.
If I don't inherit from anything, it can't be null.
If I inherit from UnityEngine.Object, json utility never fills it with data(ig it's incompatible?).
If I use ScriptableObject it requires me to create an actual instance of that so, no thanks.
Is there an alternative I am missing?
I explicitly need the object to be null by default and also be able to get a value from the json utility.
To provide a bit more context, I have this function for loading data from json:
private void LoadConfig()
{
Data.ResetToDefault(true);
JsonUtility.FromJsonOverwrite(_configText, Data);
Data.Load();
}
It basically resets values to default, overwrites the Data class and then calls the Load() function on it.
Issue is, I want certain things to start off as null in that Data class, when it's overwritten.
Thanks in advance!
public Stuff? a_nullable;
the var can eorher be Stuff or null
i assume thats what youre aski g for anywho
would you like me to go into a bit more detail?
Why would you need to inherit from anything?
Ah i see the nullability
Don't use JsonUtility
I suggest you use Newtonsoft instead
Your issue is fixed then
issue is, with json utility I can simply overwrite the entire config with any data, that simplifies the workflow if you have several types of config
is newtonsoft able to do that too?
JsonUtility is a shitty tool that has existed for a long time and it lacks the most basic features
As far as I know Newtonsoft works the same and works better on every level
Unfortunately there are issues with Unity when it comes to serializing code because Newtonsoft (and any other tool for that matter) expects you to use properties rather than fields
ok, let me look into that, should be fairly easy to replace then
And Unity has had a very poor system of conventions and it uses a lot of fields
So types like Vector3 need a bit of extra work to get working, but it is perfectly possible
that's fine with me, as long as I can make them null by default
I wonder if you could use [SerializeReference] with the default JsonUtility to support null values
Since it allows unity to serialize null values
When I tried JsonUtility I could not get null working whatsoever
Had to resort to the same system Nullable<> uses, with an explicit HasValue bool
To explain my issue a bit further, I am making a music visualizer that's also a bit of a framework?, if you'd call it that.
It offers an easy way to create new scenes and configs for those scenes, with the exception of custom data types that should be stored.
Issue arises from the fact I'd like users to be able to easily define default values that would be applied if user ones are not found in config, for example the thing seen in the first picture.
It should look like this in the class json should load into:
[SerializeField] [GradientUsage(true)] public Gradient DefaultCubeColorOverLife;
public ConfigGradient CubeColorOverLife;
Now, the issue is, I have no way of assigning the default value if the user defined one is not found in the config because the ConfigGradient is never null.
That would go for any other class and, therefore, I am looking for a way to make the class null by default if not found in the config.
Did you try serializereference?
would you mind elaborating a bit more on that?
if it's like 1 line of code, that would be perfectly fine with me, as long as the workflow is simple and consistent.
JsonUtility is unable to do a lot more
root objects, dictionaries, stuff like that
If you are going to make workaorunds for literally everything you are better off switching to a better serializer
am I supposed to just add that before the field json will assign to?
As far as I know Vector3 is one of the few instances where Newtonsoft does not work, which is only because of Unity's bad syntax
But there are examples on how to support those online
oh my bad, I thought you said newtosoft
Nah don't bother at least yet, looks like it might not work
No idea, it has been years
The doc says this for SerializeReference
ok, it sounds like I should switch to a better json serialization lib, lemme d that first
iirc none of the 'standard' Unity structs are serializable by Newtonsoft. Vectors, Color, Quaternions etc, etc
So I thought since unity uses JsonUtility internally maybe it would support that
When Unity switches to CoreCLR you will also be able to use System.Text.Json which is extremely fast and performant, and it works very similar to Newtonsoft
I would assume they also fix their shitty conventions by then
wish I could wait that long, I am close to making this fully functional and will switch to a better implementation when it's available
you assume too much, imagine the amount of breakinig changes that would cause
How is it because of unity's bad syntax?
I mean, if breaking changes are for the better, I'd be all for it, nobody is making you upgrade to a newer unity version, right?
Genuine question
Very true, but I can't imagine the update can be done without breaking changes
it's not, none of Unity Structs have [System.Serializable] so are not serializable out of the box
Perhaps the conventions do remain the same, though. I sure hope not
yes they are, the asset store
This property causes Newtonsoft to break with Vector3. If they add [JsonIgnore] to it it would not break
To be fair, this is not an issue with convention. Just a missing attribute
They already have to maintain api difference for older unity versions where it is missing newer things. So not that new
You see JsonUtility does not break because it serializes fields rather than properties
Though you could configure Newtonsoft to serialize fields and not properties, so I suppose you can work around it
But generally properties are the things that represent shareable data and/or points of access to data
sadly didn't work, I tried this and it was just always null, even when found in config:
[SerializeReference] public ConfigGradient CubeColorOverLife;
It breaks due to recursion btw
Vector3->Vector3->Vector3->Vector3->Vector3->...
which is why Unity imposes a 10 level limit on recursion in it's serializer
You could probably also impose a limit on Newtonsoft, but the better way would be to add a custom type serializer
Considering it also serializes a lot more than just this, which is garbage data. Only the xyz component is important
Here is a solution. Pretty sure these converters all fix the issues with newtonsoft
tbh as Unity has their own branch on Newtonsoft you would indeed have expected them to have fixed this
Tbf it's more of a case where newtonsoft is annoying and tries to serialize any property it can, regardless of if it should, such as vector3's normalized property, etc. You can disable recursion in the serializer settings though.
You can't really blame a tool that is designed to serialize properties
How would it know?
which is why we do not rely soley on Reflection when writing serializers
Newtonsoft doesn't assume what it has to serialize, that would be silly. It's up to the developer to explicitly ignore properties with [JsonIgnore]
BTW here is the converter for Vector3, if you just strictly want that one for example: https://github.com/applejag/Newtonsoft.Json-for-Unity.Converters/blob/master/Packages/Newtonsoft.Json-for-Unity.Converters/UnityConverters/Math/Vector3Converter.cs
yeah, I use that package
ok, so if I got this right, I should switch to newtonsoft, add the repo as a submodule, and use that since it already has color serialization, correct? (nvm, it doesn't have the gradient de/serialization, which is what I need)
It mainly just annoys me when I can't tell it "hey serialize properties, but just ones that don't have logic". Like that could just be a serialization setting flag since it already expects properties. So I instead have to make a custom contract resolver to fix that project-wide (which is annoying to deal with imo).
how does one define "logic"?
now we're doing TURBO reflection 😉
I want to create a tool/system for my game, and I'm stuck on finding a way to put it all together.
I'm not keen on the idea of my GameObject having 8 different components, initilisation is a challenge (especially when one component relies on another), and it honestly doesnt feel right to lay out everything like that
You could add a component that handles initialization and maybe also ticking the components if needed
at the same time, there's no way I'm putting everything that would be in each component, into one single class
This is what I did when my character's components started getting out of hand
it is nice to have something that's "in control", yes
not sure if it helps, but here's an overview of the way everything is connected. Each block would be a different component
I dont have any plans for tilebased stuff like unitys 2D system
If it is an auto property or not
Hm, that does sound tractable
Yeah it is, I just had to do it manually
Solved all my unity newtonsoft problems instantly
I was thinking of properties that just return or set another field
but then that field would need to be serialized anyway
so there'd be no point in serializing the property
my tilemap system is purely so I can keep track of the design of the garden and so I can generate it accordingly, its not related to the context Unity has for the term
As in with an explicit backing field? Because I don't see why you would ask for such a specific use case
Why not just specify the property should be ignored with something explicit like an attribute? If you were to put in the assumption that everything without a backing field has to be parsed then that is going to introduce some weird unexpected bugs
I'm wary when it comes to having a class derive from MonoBehaviour, I dont really know if there is a catch to it. But I'm thinking something like this
public class GardenBase : MonoBehaviour
{
void Awake()
{
//different elements constructed here
//like a Rectangle to define the bounds of my garden
}
}
public class Garden : GardenBase
{
//as GardenBase defines all the parts of my garden system
//this Garden class is where I can write the actual logic
}```
I want to avoid my Garden class having a giant chunk of initialisation stuff, and as its purely a system of related components, it seems logical to have a base class take care of setting out all the parts of it
Perhaps "Rectangle" shouldn't be a MonoBehaviour at all
oh its not, its a struct
ah, okay
h hh
I mean, you can do this if it feels more organized to you
It's also possible to make a partial class and split a class into different files
I've never needed, or wanted, to serialize a property that has logic on it in any type 🤷♂️
If you were to put in the assumption that everything without a backing field has to be parsed then that is going to introduce some weird unexpected bugs
It already tries to do that though 🤔 , unless you put the attribute to ignore the property. That's a problem if you don't have access to a bunch of types and you run into cases, like Vector3, where it has a logic property recursively serializing itself. So you either have to make a wrapper type (per type), a converter (per type), or a contract resolver. Instead of just letting me specify that I want to exclude properties without backing fields.
Anyways, this is just something I've run into in many work projects, so just a slight rambling.
yes -- nomnom's problem is that Json.NET is overly aggressively and tries to serialize every single property
you can add the [JsonObject(MemberSerialization.OptIn)] attribute to the class and serialize whatever you want explicitly
Personally I like having base classes for things like this. If you know you're going to be making a lot of different gardens then it's not a horrible idea.
Alternately you could have a separate script called GardenBase, set your variables up in that component and reference it in a specific Garden. Apparently this is the "better" method but I find it kinda messy lol
If you know you're going to be making a lot of different gardens then it's not a horrible idea.
This is what has made me wary for a while, theres only actually going to be a single Garden
One class or one use of the script throughout your entire game
definitley not a one script game
I just mean theres never going to be variants that derive from GardenBase
nothing like SnowyGarden : GardenBase or ForestGarden : GardenBase
Oops, I mean that when these don't have to be parsed
Regardless I'm not sure why you can't just insert an explicit attribute. Everybody does this
That's a problem if you don't have access to a bunch of types and you run into cases, like Vector3, where it has a logic property recursively serializing itself.
This is very much just bad design, though. If they didn't default to a shitty serializer they would have likely fixed this on their end already
But now you have to resort to converters since they choose JsonUtility over Newtonsoft
public class GardenBase : ScriptableObject/MonoBehavior
{
public Radius[] gardenBounds;
public Radius GetRadiusAtIndex(int index) => gardenBounds[index];
}
[Serializable]
public struct Radius
{
public float radius;
}
public class Garden : MonoBehaviour
{
public GardenBase gardenBase;
}```
Would something like this work, maybe?
The only issue here is that you can't serialize everything, but this is something I have never had an issue with. If you serialize something, it is always a type that is supposed to be serializable. You would not serialize a whole Monobehaviour, for example. You would have a data object that is serialized. (it would not make sense anyway because you can't deserialize it back into a Monobehaviour)
One central garden base per scene, which you just access indexes of. After defining them in the component
I havent worked with ScriptableObjects yet, but are they also not really intended to create many variations of a base?
Nothing wrong with using SOs as base. They are similar to any other regular classes
You'd only need one. Or one per scene to define them
The array would store loads of different, pre-defined garden shapes. I actually used them for an audio setup which works pretty nicely. Same objects for the entire project
they main difference is that SOs can have instances in the asset view since they are...assets
ScriptableObject lets you create your own kinds of unity objects
Dude, I am so thankful to you.
This fixed 12 hours of my pain in 10 minutes 😭
I simply replaced:
JsonUtility.FromJsonOverwrite(_configText, Data);
With:
JsonConvert.PopulateObject(_configText, Data);
And everything is working flawlessly now.
I have to do some more testing with this but it's looking really good!
notably, these objects aren't derived from Component
This lets you create assets out of them
much like a Material
you can totally just create a material through code and never had an asset
(and this happens very frequently, in fact)
ScriptableObjects are good for when you need to share a piece of data among many scenes or assets (prefabs, other scriptable objects, etc.)
Note it doesn't work the same so you should make sure the data is still properly transferred.
Glad it works 👍
They aren't a good fit if you just need to reference a piece of data once
That's where you might use [SerializeReference], along with a package to provide a type selection UI
That lets you serialize a field that holds a non-unity-object
and, vitally, lets you store any derived type
It is, I structured my data mostly logically, which newtonsoft seems to fit perfectly.
Thanks again!
public class ParentSO : ScriptableObject { public int parent; }
public class ChildSO : ParentSO { public int child; }
[Serializeable] public class ParentPOCO { public int parent; }
[Serializeable] public class ChildPOCO : ParentPOCO { public int child; }
Given these classes:
public ParentSO foo; // fine, can hold instances of ParentSO or ChildSO -- it's just a reference to another unity object
public ParentPOCO bar; // bad, can hold a ChildPOCO, but its "child" field won't be serialized!
[SerializeReference] public ParentPOCO bar2; // good, will correctly store both ParentPOCO and ChildPOCO
That could be useful, for the moment I'll see how much progress I can get without a scriptable object
Unless theres some killer feature or advantage that SO have over me writing a generic base/derived combo
As far as I know, the biggest differences were mentioned by Fen.
ah, missed that one
My main reason is ease of use lol. I'd rather use a scriptable object than remake scripts if I'm going to use them a looot.
Even with Copy/Paste
yeah, if I was going to create many variations of my Garden class, I can see the benefit
essentially everything in the diagram I posted earlier, you can think of them sharing the same namespace
I usually use SO's as containers for a POCO data classcs public class ThingAsset : ScriptableObject { public ThingData data; }
[Serializable] public class ThingData { ... }```
This way I don't always need a SO instance if I want to deal with ``ThingData``
But can easily use SO to reference a ThingData if I want to use a premade one
(Not necessarily related to your discussion - just throwing it out there)
Can scriptable objects and their contents be serialized to JSON format? I assume they could be
Then again, I have almost no knowledge on the subject of saving stuff between play sessions lol
Not really - anything inheriting from UnityEngine.Object isn't supposed to be serialized to JSON
Which is another great reason to not directly store the data in the SO but in one of its fields instead
Hm, makes sense. A lot of serialization seems like really well made trickery
I mean, you could totally serialize data from a ScriptableObject and then shove it back into another instance later
But, much like Components, you aren't meant to construct these objects on your own
I'll let you into a secret. Serialization is easy, it's the deserialization which will bite you in the arse
I give many of my SOs a guid field. I use that to serialize references to them
and to look them up when deserializing later
How so? 👀
Serialization is Humpty Dumpty falling off the wall
Deserialization is the job of all the king's men :p
because deserialization can have consequences, especially for properties so you have to do it right and in the correct sequence
Good analogy lol. My few experiences with it have been.. Somewhat straight forward.
I planned on having a Content base class, and classes that inherited from it, saved in a save file somwhere and read from there
If creating your objects includes side-effects, or the order of operations is very important (maybe Foo needs to have its Bar assigned before its Baz assigned), it can get very icky
Cyclic dependencies do not induce joy
Now that I have some more coffee (and had to do some stuff), yeah that's fair, albeit it's still weird how props like that are serialized by default to me. Like if I serialize the inputs (adjacent fields), I wouldn't expect an output (the getter) to be serialized too. But it is what it is, so I just live with it lol.
The only issue here is that you can't serialize everything
In one project we had to serialize an ecs world (so everything), and we used json just so we could quickly test with world snapshots (couldn't do binary saving yet due to data ambiguity in a few spots). So that was an issue if things stored vectors anywhereAnother one was when we saved settings to json that had some vectors; that one is the more basic case anyhow (and we ended up just switching to toml).
hey fellas, just watched Brackey making an audio manager, and that got me questioning, whats the difference between coding your own audio manager and using FMod?
Almost all of my serialized data is just GUIDs and simple types (bools, floats and strings)
nothing, if you implement a complex enough "audio manager" :p
FMOD makes it easy to combine multiple pieces of audio into a complex event with randomization and controls
You can totally do all of that yourself (I did for a while)
I see
actually, now that im writing the base class, I've hit a similar problem as before.
public class GardenBase : MonoBehaviour
{
GardenFloor Floor; //defines the bounds of my garden, can also trigger events ie OnFloorClicked
void Awake()
{
//option 1
Floor = GetComponent<GardenFloor>();
//option 2
//dont use a component, hardcode GardenFloor into GardenBase instead
}
}```Option 1 doesnt avoid the fact that I dont want a bunch of additional components, and option 2 also isnt really a good solution either.
but are there any downsides to doing it yourself? (beside taking a tad bit longer)
cause if not then I guess I wont touch FMod, unless it brings in some very nice QoL changes to the project as a whole
I was really on the fence about FMOD for a while
because I figured it didn't do anything I couldn't do myself
switching to it was certainly a Process (tm)
its like re-learning FLstudio all over again to me
and yeah what I'm thinking rn is exactly how you've phrased it too
GardenFloor is an integral part of the Garden, it defines the actual physical form of the garden, and most other elements rely on the Floor (like getting dimensions for a texture)
Depending on how it's set up, there can be issues with doing it yourself lol.
I opted for a physics material based setup and it took a lot of polishing to get working nicely. So that's probably the main consideration
basically, if you don't feel that you're being creatively stifled by DIY, then give it a crack
I personally think it's worth it, ya
fair point of views
you might not need fifty-dimensional underwater basketweaving features in your project
Plus, it allows you to tie in custom things while knowing exactly how the code works 
Adding haptics to the collision was like 10 minutes of work with mine.
Have you used Live Update yet?
well, more or less I would just tip my toes in Fmod a tad bit before getting back to DIY (cause ive coded it for like half a day and would be FUMING if I change to Fmod after all the work ngl)
Oh yeah, that's very cool
I understand you can even use that in a built game
I used FMOD embarassingly long without realizing you can use that to modify it in real time instead of having to quit playmode and rebuild banks 🤦♂️
Recently checked out the FMOD profiler, its pretty cool too
oh god thinking of which is there anyway to make the load-time to playmode faster
it takes forever to load imo
I do wish I could wrap my head around the fmod + studio workflow. It seems so nice, it just never "feels right" when I try and integrate with it 
Make sure to read it all though, there are some caveats
I enter Play Mode in like half a second. It's pretty neat.
I have built the entire game to behave correctly with Domain Reload off
I recently discovered an interesting behavior caused by disabling Scene Reload!
Doesn't Awake (or Start?) not re-run
Also someone asked some days ago if FMOD clutters your workspace
I'm garbage at answering stuff like that on the spot, but the answer is the opposite since you don't have all those audio files dangling around
Unfortunately I just forgot what it was 
It had to do with physics.
I think I was having a problem where the pivot point of a joint was apparently changing even though literally nothing in the scene asset changed
Oh man now I have to go back and look at that again
Joints are already cursed
The problem would go away after a recompile
I'm pretty sure theres something fucky about joint initialization
since that reloaded objects
Joints are always fucky
I wouldn't really call audio clips cluttered. I have one folder for 90% of my audio and it's organised by type
But, this isn't exactly code related 😛
Made an active ragdoll system like 2 years ago. Didn't feel like touching it ever since
I use PuppetMaster and pray
Now that I'm using FMOD, I keep all of my "source clips" outside of the Assets folder. I also don't version-control my audio banks.
It's pretty tidy
Yeah same
This does add another criteria for correctly going to a random old commit and having a working build
And, you know, at that point -- I might as well not version control my FBX files, since they're exported automatically from Blender...
I just need the importer settings
I'm getting bad ideas!
Is there a good generalized guide about the fmod workflow that you've used? I want to use it in the future, but as a non-audio person it just hasn't clicked yet.
So imagine you want to make a "bullet impact" sound
that might be several smaller sound effects played together
a thunk sound, a gore noise
FMOD lets you create a single "Event" that sequences sounds
It can randomize which sounds it plays, apply filters to those sounds, and combine smaller events into larger events
If I want a "low violence" mode, I can add a parameter that controls whether any of the gore sounds play
sorry if this sounds ignorant but can't you just make an additional Audio Manager that will select those sounds based on a given chance given?
You can punt a decent bit of logic out of your game and into FMOD studio
Of course -- but do you want to? (:
Wish I could recommend something but im afraid that I didn't learn it the "right" way, I just messed around
fair point
And still keep learning new stuff
I did that for a while
But I guess you can start here https://www.fmod.com/docs/2.01/unity/user-guide.html#accessing-your-fmod-studio-content
and Unity now has the Audio Random Container for basic stuff
the docs are uh
slightly borked
oh words?
i've had issues with them just sending me to the landing page
I think I had to switch to a slightly older version of the unity integration
(that might be fixed by now; this was half a year ago)
Btw @heady iris Do you use spatial audio with FMOD? And which one
Yeah but do you use like HRTF
I use Steam Audio's spatializer instead of FMOD's spatializer in my events
Directional audio is way more accurate
I wish I could use Steam Audio, but I'm on an ARM macbook

pretty sure it doesn't work on that platform
I just use the built-in Spatializer
I had problems with it panning WAY TOO FAST for a while. I eventually worked out that FMOD was trying to output 5.1 surround sound
@eager yacht And others, if you do have FMOD questions throw them in #🔊┃audio so maybe we can get some life to that channel too
Looks like it's supported since May last year
https://github.com/ValveSoftware/steam-audio/issues/186#issuecomment-1485492015
well -- I should probably be working right now, so I'll do that first 😉
Wait what
Oh my god
I use Steam Audio for all my game jam games. So nice.
I was looking into this a few months before that point
But I swear I've checked more recently

WELL
I'm going to look into this very soon
One downside I have noticed is that the Steam audio spatializer really only supports mono sounds. So I use default spatializer for near sounds that I want to be stereo and then fade into spatialized sound when further away
Unless im missing something
Anyway yeah I'm gonna stop spamming this channel
hey fellas, back at it with yet another question
is there a difference between using, say
void OnSmth
and
private void OnSmth
it's just a style thing, the default is private if you don't specify it in C#
thank you!
Hello! Could someone please help me to understand how to handle different mobile screens in Unity?
I mean case when we have different aspect ratios. I feel like I had to cut part of the game, not shure how to handle it better
I feel like in one case I can just add black lines on the sides and it will be ok. But in case I have different resolution when not entire content fit screen, I'm a bit confused what to do.
Are you referring to UI/Canvas specifically, or the scaling the scene/camera to fit a device?
Game itself. I do understand that I don't want scale my game, but I feel it may cause some issues if I dont
I mean I feel scaling game itself will cause a lot of issues, but may be it's given to support different mobile resolutions.
Ah, im not as familiar with that, my suggestion would be to try letterboxing or pillarboxing depending if your game supports horizontal or vertical or both
Do you know by the way, it's good practice to use camera to calculate game area? In case my game is 2d space shooter (enemies flying from the top, player on the bottom).
Or I better use world coordinates direclty?
This is one of my main concerns too, since right now I'm using camera (to world position), but I feel when it's resized I may have inconsistent behaviour.
You can adjust the resolution in the Game window to see how your game will look under different conditions, if your able to use world space youd likely have more control over positioning things, but if all your positioning depends on the camera bounds, you could try using the frustrum or screen resolution to determine relative positions (assuming your FOV is fixed)
At the moment not all position depends on camera bounds. For example when I create level it's easier for me to place enemies by hand in specific position or coordinates (I have scriptalbe object config etc, so it's more complex than by hand but it's not important here). I assume if I will use camera bounds I will have to adjust those via some calculations, and it looks much more complex in this case than just using world positions for all. And enemy out of screen depend on camera.toworldposition. It's just a lot of guide use camera.toworldPosition for some reason, that's why I'm a bit confused.
I think thats fine, ScreenToWorldPosition does exactly as the name suggests, when you want to take a pixel space location from the screen/camera, and convert it to a position in the scene world instead, I dont see anything wrong with that approach if it helps you position things where you want them
I feel like I'm going crazy. Using Unity 6 with the render graph api, and when I try to render a camera to a render texture, the resulting texture is super flickery...but only when my laptop is plugged in? I don't even know how to begin troubleshooting this
Well, it didn't do it in a build, with or without power to my laptop, so... Setting this aside for now, I guess
IF i use this code to get the surrounding filled out tiles of tile X(the center one of the image) I would expect to get a debug log that is as follows:
false, false, false,
true, false, false, false, false, false
But i get what i get is the following:
false, false, false, false, false, true, false, true, false
Why is the order so wrong and why is there a second true statment ?
It should be surroundingOffsets[x * 3 + y]
or y * 3 + x depending on how it's set up
omg thank you, that fixed it. But why is it x*3 ?
You can calculate on paper how it behaves. It has to check all values from 0 to 8, if you do x + y it repeats values between 0 and 4
Put Debug.Log($"x = {x}, y = {y}, x + y = {x + y}, x * 3 + y = {x * 3 + y}") inside the inner loop
i get how before it looped itself and skipped values and i get how it now uses each value once but i dont understand how its still in the correct order as y=0 and x=1 results in the elemnt 3 being used as offset wich means that the block on the left is checked and assigned to bool3x3[0][1] wich would be the corect one actually. my brain is too broken rn
That just depends on what values are in the offsets array. It works because the value (-1, 0, 0) is set to element 3 which corresponds to [0][1] in the surroundings matrix
Although it's unusual that it's [y][x] instead of [x][y]
i mixed up rows and columns, but i do understand it now and im happy it finally works
I need to create a dll that can be used in unity 2022 or newer. The project will be compiled into dll outside of unity and then used in unity by importing the dll. My question is, which .NET version my dll should target if i want it to be usable regardless of unity api compatibility level. Should i target the .net standard version used by unity or the .net framework
depends if you need items specific to .net framework, .net standard is just .net framework with some stuff removed
No i dont need items that only exist in one but not the other, so which .net should i target if i want the dll to be able to be referenced in both .net standard 2.1 and .net framework 4.8 (the .net supported by unity)
I'd probably go with standard unless something specific you need from 4.x not present in standard
iirc standard makes it easier for multi-platform
Which version of .net standard?
I read the documentation and .net framework support in .net standard 2.1 was N/A so definitely not the 2.1 version
I'd do 2.0
the latest is 2.1 though
https://docs.unity3d.com/Manual/dotnet-profile-support.html
Hmm okay thanks. But does .net framework 4.8 actually support .net standard 2.0 dll though? I only found the documentation for what .net standard support but not what .net framework support
actually now that I read this I'd go with .net standard
Support for managed plug-ins compiled for .NET Framework is limited when you use the .NET Standard 2.1 profile in Unity. Any .NET Framework APIs that are also present in .NET Standard are supported. However, the .NET Framework API contains types and methods that are not available in the .NET Standard 2.1 profile.
idk the .net framework might give you more options with other .net libraries
iirc it should. give it a try.
I usually use .net standard 2 ones
hey guys
sometimes, my character will hold a weapon with both hands
do I have to recreate all animations for it to hold it with both hands?
or I can make something that only influences where the arms are
probably more of a #🏃┃animation question than coding.
I'm using fusion to try to do active ragdoll multiplayer and my player 2 client keeps throwing this error and not rendering the physics. Any ideas?
I see, apologies! Will ask there
not sure if this is the right channel, but i'm having an issue where while constraining my 2D player character's movement to a spline, the player character rotates if the curve is not directly horizontal to match the spline, wheareas i want its rotation to remain constant. I've tried freezing rotations in the character's rigidbody, but that doesn't work. any ideas on how i can keep the player character from rotating?
is it possible to assign a sprite from my assets to a sprite renderer via code. Without assigning it manually in the editor beforehand?
ofc is possible
the question is, why
can I use addressables for it?
sure thats what they're for
I am making a cardgame and I want to store decks in a database meaning the database will have lists of the card IDs as "Decklists".
To load them into the game I made a prefab for a "blank" card that has a sprite renderer for the cardart. I want the the cardart to be assigned into the prefab's sprite renderer when a Gameobject is created using that prefab.
and as to not have to create prefabs for every single card I want to use a generalized one that assigns name, art etc through the assets
you can def do that even if you did have an inspector
you could potentially make it addressable/asset bundle though anyway for maybe external assets
okay thanks i will see if i can find something
!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.
Hello, I want to make a moving platform for my game and I tried different things but nothing really worked. I got this version that still doesn't totally work and I need your help please. I use a CharacterController for my player, a rigidbody (kinematic with interpolation set as interpolate) for the moving platform. I do not want to use parenting. My current code is this, the player can stay on the platform but when I move in the opposite direction as the platform my player move slower. I think it's because the character movement are in world position and not local to the platform and I don't know how to correct it : https://hatebin.com/vdjdspcprv
depending on your coding level, you can try this free asset : https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131
it can handle the player on moving platforms. it has examples as well to help you out.
Is it bad for performance to modify material properties every frame? Does it like recompile the shader or something
Nah, it just sets the new value of that property in your shader. Next time the shader executes it's code, it will use whatever value that property is currently set as
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
is there a way to make it so you can stretch the size of the window?
Is there a way to use coroutines to move something for a certain amount of time?
which window are you talking about?
nvm i found what i needed
yes, it's a pretty typical coroutine thing
Hello, wanted to get some opinions on this. Is it better to make delegate voids / events and have all your systems (like UI manager, audio, etc.) subscribe to them, or simply create a function which calls all the neccessary functions directly via static instances? In my game I'm kind of stuck with a combination of the two and was thinking of trying to eliminate one in favor of the other.
Combination of different systems is not always bad. Assuming they don't mix their responsibilities.
also if you are not familiar with Singletons, i would highly recommend you also make use of them. They can reduce your workflow really strongly.
in generell i think working with events is cleaner than creating a reference to everything.
as dlich metioned, a combination of events/references is not always a bad idea
you would find out what is clean and requires less work.
I see, what kind of purpose would static references be good for? I kind of call all my SFX on my AudioManager via direct calls as I found it easier rather than create a million subscriber functions in the AudioManager.
Singletons you mean like having a static Instance member on classes so you access their functions by doing, for example GamaManager.Instance / GamaManager.SIngleton?
ye
Well, if it's some static methods on a manager script or something, it's fine.
You can proxy to the singleton via static methods too
well for example I have a UI script which can show some effects on screen. Is it better to make it subscribe to events like the player taking damage, or make some function on the player or gamemanager to instead call the effect via a static instance? Or does it barely matter so either is fine
It depends. You usually want a many-to-one relationship, rather than one-to-many. If your gamemanager needs to subscribe to many events(and the number might potentially increase in the future), that's not a great design. In this scenario, it's better for all the objects that need the gamemanager to do something, to call a method on it(via a singleton or static method).
I see, thanks for the tip! My gamemanager definitely has a bit too many events, like there are 16 or so right now :/
Then to trigger one a script can call a function on the gamemanager which makes it do some things related to the event (e.g. update score) and then calls the eventn notifying the subscribers. It's definitely getting a bit messy at this point so maybe I can remove some of the events and make it just call the functions those events would eventually lead to anyway
Maybe rething the dependencies that you have in your project. Sometimes it's better to pass a reference to a directly related object, instead of using an intermediary, like your gamemanager. For example, if you no have a chain like player - gamemanager - uiManager - uiPanel, it might be wiser to just pass the player reference to the uiPanel, and let it subscribe to the necessary event, so that the dependency chain becomes uiPanel - player.
oh yeah thats so smart, thanks for the idea, I will actually try it out
how did we get to that daisy chain
Just an example. In theory you could have something like gamemanager subscribe to a player event, like TookDamage, then call a method on uiManager like SetHPBarValue and the uiManager call something like SetBarFillValue.
It's not weird for a beginner to have something like that.
what's the consensus on having GameEvents, UIEvents, etc classes?
Where their only job is to expose events for others to invoke/subscribe to?
kinda like unity's QuizU sample
If it fits your overall project design, sure.
This kind of questions are usually a matter of preference and context.
I'm just concerned about potential pitfalls tbh considering I'm not used to this design pattern this way (I'm familiar with events tho)
for some reason UI elements is deciding to give me a NRE
then you haven't set something properly, probably?
can't tell you much without any info
UIEvents.OnStartBuildingClick (UnityEngine.UIElements.ClickEvent evt) (at Assets/Scripts/UIEvents.cs:26)
UnityEngine.UIElements.EventCallbackFunctor`1[TEventType].Invoke (UnityEngine.UIElements.EventBase evt) (at /Users/bokken/build/output/unity/unity/Modules/UIElements/Core/Events/EventCallback.cs:64)
UnityEngine.UIElements.EventCallbackRegistry+DynamicCallbackList.Invoke (UnityEngine.UIElements.EventBase evt, UnityEngine.UIElements.BaseVisualElementPanel panel, UnityEngine.UIElements.VisualElement target) (at /Users/bokken/build/output/unity/unity/Modules/UIElements/Core/Events/EventCallbackRegistry.cs:228)```
Assets/Scripts/UIEvents.cs:26
check what you're trying to dereference there
im calling my nodePlacementSystem.EnableNodePlacement(); which is instantiated in the UIEvents file
then nodePlacementSystem is null
how can i make it not be null?
...set it?
Hi, I am working with newtonsoft json and my custom data types.
I made it all work, but there is a small thing I'd like to make better if possible.
Here's an example of my data type:
[Serializable]
public class ConfigVector2
{
public float X;
public float Y;
public ConfigVector2()
{
X = 0;
Y = 0;
}
}
// Some other code I have
Now, it ofc works as expected, but in order to allow for default values set by scene creators(I am making kind of a framework, not a game), they have to use a specific approach.
It consists of defining the default value and config value:
[JsonIgnore] public Vector2 DefaultCameraClippingPlanes = new(1, 1000);
[ReadOnly] public ConfigVector2 CameraClippingPlanes;
When the config is reset to default values, assign null to the config value:
public override void ResetToDefault(bool silent = false)
{
CameraClippingPlanes = null;
}
When the config is loaded, right before the OnConfigLoaded event is raised, assign the default value to the config value if it's still null:
public override void Load()
{
CameraClippingPlanes ??= DefaultCameraClippingPlanes;
base.Load(); // Invokes the OnConfigLoaded event
}
Let me explain what's going on here.
With regular values, such as int, string etc., simply assigning the default value directly in ResetToDefault() works just fine, because if not found in the config, it'll remain as it's default value, and if found will be fully overwritten by the new config value.
Issue with custom data types is that they usually consist of multiple fields/properties.
Good thing about JSON is that it allows you to not define what you don't need, e.g. you only wanna change the X value of a Vector2, go right ahead, Y will just not be loaded.
Whilst this is excellent, it also introduces an issue of the Y remaining as the default value if it wasn't null at the time of loading(you assigned the default value in the reset method).
I am open to any suggestions, thanks in advance!
Oh yeah, one more thing that could help with understanding how the code flows is this:
private void LoadConfig()
{
// Using ResetSilent because the OnChanged event will get triggered by Load() anyways
Data.ResetToDefault(true);
JsonConvert.PopulateObject(_configText, Data);
Data.Load();
}
Please @ me if you have any recommendations.
can anyone here posit why my 'CustomPropertyDrawer' is not showing up.. not sure if this is the right place to ask this...
I have some working already.. but on this particular object, the inspector is looking very 'vanilla' and it is not showing up...
Does anyone know if there's something special you have to do with your textures to use them with a URP Decal projector?
Transparent parts of the texture I'm projecting seem to mess with shadows.
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
we don't allow these kinds of posts here. we provide free community support
try doing it yourself and if you encounter any problems you can ask here for free
bump
@novel monolith please also do remove both your job posts
i have this one little problem for some reason my animation does not transfer to what it should when the condition is met in unity if someon can help me fix ?
not if you don't provide any info. sounds like you have an #🏃┃animation issue rather than a code issue though
There is a bomb attached to my character's left hand, but I want this bomb to be attached to both hands of the character. When it is attached to a single hand, it can cause problems in character movements and animations. How can I solve this problem?
probably with IK, not code
do you know what IK is?
yes
ok try googling for how to do that with unity
i know it's the tool for the job but idk how to do it lmao
it's not a coding thing, maybe ask in #🏃┃animation
We need context. Open your animator and see if your "condition" is markedchecked when it should. If yes it's a animation problem, so wrong channel, if not say more 😉
bump
I've made an event class, but I cant find a way to invoke the event.
namespace ZenGarden.Events
{
public static class MouseEvents
{
public static event System.Action OnMouseClick;
}
}```
```cs
using ZenGarden.Events;
namespace ZenGarden
{
class Garden : GardenBase
{
void Update()
{
if(Input.GetMouseButtonDown(0))
{
MouseEvents.OnMouseClick?.Invoke();
}
}
}
}```I get an error saying `The event MouseEvents.OnMouseClick can only appear on the left hand side of += or -=`. But I dont get why as all I'm doing is invoking the event, `+=` is only used to make something subscribe to the event, wont it?
I have a different class that has subscribed to the event correctly with MouseEvents.OnMouseClick += HandleOnClick;
just unsure how to actually call the event
isn't it just MouseEvents.OnMouseClick()
Yep, not an event for me (i don't understand them), just using a method in a static class
If you need events you need to subscribe to them, why checking inputs in update if you want events for mouse i don't get it
Invoke() is what calls the event, its not a method
public event System.Action TestEvent;
void Update()
{
if(Input.GetMouseButtonDown(0))
{
TestEvent?.Invoke();
}
}```This works without an issue
@wheat spruce https://stackoverflow.com/a/61652602
I dont know if thats much good, totally different use of events to my static class, plus I dont think interfaces can be static
event keyword is the problem here
Outsider classes can only subscribe to it but they can't invoke it because it is marked as event
To be clear, that keyword is not necessary
How could I make the event so it can accessed anywhere like static easily allows?
Read what I said 🤔
Encapsulation I suppose
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/event
It's like an access modifier in the sense that it prevents other classes from raising the event (invoking it)
ah, I see
I've always felt a bit unsure with actions/events in general, but thats mostly out of not using them a whole lot
They aren't that scary after all, try to get used to them, useful stuff
I remember it took a while for me until it clicked
hopefully thats how it'll be once I finish the events class. I'll be doing EventArgs so I can pass whatever I need around, all stuff I've done before, so doing it a few more times should be good practise
im not super sure since i haven't used them, but from the SO post/answer:
events can be explicitly implemented like properties, but here where you haven't implemented one, it'll get an automatic implementation
and similar to how a property like int x { get; set; } has an internal backing field, an event also has one, which is private like with a property
and Invoke is part of the private backing field
so with an automatically implemented event, only the declaring class can invoke it
I remember when I had no idea the idea of how to do MouseEvents.OnMouseClick.Invoke(); to call an event, and same with MouseEvents.OnMouseClick += HandleOnClick; to subscribe
its just practise at the end of the day
Is there such a thing as non-automatically implemented event?
see the SO answer i posted
with that you can have an explicit backing field which you can specify access level for
idk why you'd want to do that, given the entire concept of events, but it's there
bump
I'd try rephrasing the question if you can't get answers
IMO it's good to have the actual question asked briefly at the beginning and then provide details
To sum this question up, I created a class, e.g. ConfigVector2, that I wanna deserialize with newtonsoft json.
It works well, but if I want both X and Y components to be overwritten when loading the new data, I need to do that explicitly in a function that gets called before loading the json data.
I am talking about the case where you defined X in the config but not Y, which is what I want users to be able to do, but it also complicates the workflow of a someone implementing this data type into their config.
Whenever I do that people ask for more details, so I provided more details in the original message.
It's a question that kinda requires them, here's a summary tho.
One option would be to use nullable types,l ike float?. This would let you indicate that no value was provided at all
I didn't mean "don't include details", I just prefer hearing the question first and then the details
I'm pretty sure this leads to allocations though
ok, but if you were to assign the default value in ResetToDefault(), it'd still be set to that if Y is not found in the config, right?
again, this is fully functional, what I wanna do is simplify the workflow with custom types so you can simply reset the value in ResetToDefault() and not have anything to do with the Load() function
I guess I'm not understanding the problem, then. If your config has a value for X, but not Y, then you wind up with Y=1000 in the resulting object.
if you use the approach I suggested where you set it to null in ResetToDefault(), and then assign the default value in Load() if it's still null, it'll work properly, this requires an additional line for each variable tho and is not very intuitive
Maybe you can give me an example of where the problem is? This sounds fine to me.
You write the default, then apply the data from the config file
or does PopulateObject wind up setting the Y field even if the config didn't have a value for Y?
no, that's what I'd like it to do, as of rn, it just leaves Y to whatever you set it to in ResetToDefault()
What would the correct behavior be?
the way I'm thinking of it is, if the data type is found in the config, overwrite it with whatever data is available as a whole class, not just it's members
That sounds counter-intuitive to me. I would expect anything I don't explicitly provide to keep its default value
if I specify X=10, I'd expect to get X=10, Y=1000
yes, it would be counter intuitive in 99% of cases, but not this one
let me show you why, give me 5 minutes
Ok, so where it starts being a problem is if we introduce colors.
If I define a color gradient like this:
"ColorOverLife": {
"ColorKeys": [
{ "Color": { "R": 1.0, "G": 0.4 }, "Time": 0.25 },
{ "Color": { "G": 0.0, "B": 1.0 }, "Time": 1.0 }
]
}
You would expect it to look like it does in the first picture.
However, if we don't overwrite the default data, it'll end up looking like the second picture, since it's only adding on top of the default gradient which looks like this:
"ColorOverLife": {
"ColorKeys": [
{ "Color": { "R": 0.0, "G": 0.4, "B": 1.0 }, "Time": 0.25 },
{ "Color": { "R": 1.0, "G": 0.0, "B": 1.0 }, "Time": 1.0 }
]
}
Does what I'm asking for make sense now?
Sounds like you have bad defaults!
🤦
Perhaps there's a distinction to be made
The default value for the Color field could indeed be white
But the default value for individual parts of a Color could still be 0
I think I know what you might be suggesting so let me make sure.
You'd like the default color to be defined as black, so that when the color is added via config, instead of adding to some random colors, it's added to black and looks correct, right?
If that's the case, it won't work.
As I said, this is not a game, it's sort of a framework that others can use and default values allow them to easily define how things would look out of the box.
Imagine if someone installed the visualizer, and instead of seeing the thing in the first picture saw the thing in the second picture.
I would argue that, at least, in case of colors, the way this works by default is counterintuitive.
Having a Vector2Int start position inside of the Tilemap, what is the best way to find the nearest position with no tile in it?
Just because the default value of R, G, and B for a color is 0 doesn't mean that you can't have:
- a default Color that is white
- a default ColorOverLife that makes the particle white
There's a difference between "no value at all" and "a partially specified value"
Perhaps that's where your problem lies
{} -> it creates a color that is white, because we didn't specify a color at all
{"Color": {}} -> it creates a color that is black, because we didn't specify the R/G/B values
{"Color": {"R": 1}} -> it creates a color that is red
yes, that is exactly what I want, how to achieve that tho?
probably just looping until you find one?
how would you handle multiple possible results
the only way I could think of is setting the value to null, and then after the data is loaded, if still null, assign the default value, which brings me back to the original problem, not user friendly
speaking of tilemaps, are those only suitable to be used with stuff like Sprites/Tile?
I'm implementing my own tilemap system in my game, but I figure if theres enough general use with the unity tilemap, it could save me a lot of trouble re-implementing 100% of that system myself
A tilemap can only keep track of Tiles, and the TilemapRenderer won't just render everything attached to the tilemap
However, there's nothing stopping you from creating tiles that instantiate prefabs
(in fact, this is built-in to Tile, I'm pretty sure)
These prefabs can contain Renderers of their own
and whatever else you want
The tilemap will only understand that you have tile X in cell Y
I have a question, im coding a game which i want to publish january - february, if I need help, can I just write here and ask questions or how does that work?
I'm not using my tilemap to actually create anything in the scene, its just used as a way to store data to be used down the line
yep !ask and https://dontasktoask.com
: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
okay
In this case, it would be better to start from the startPos with the square of 1x1, and check each tile, starting from e.g. top left and moving clockwise. The square will be increased in all four directions with every loop, so 3x3, 5x5, 7,7 etc., and the process is stopped once the empty tile is found.
I just feel like it will be better to implement with 2D Raycast? This means, shooting a Ray in the four directions, but I wonder how it works with diagonals and twisted paths
I have an editor tool that works like this
I paint on a tilemap to place crates in a Giant Crate Room (it has a lot of crates)
Then I run a script that interprets the tilemap to spawn prefabs
I need a database for my cardgame. It's supposed to store user logindata cards and decks. I've used MsSql before but I would like to know if there's a solution for this provided by unity directly, since implementing it was a pain in the ass last time.
with squares, you don't get the actual nearest tile
also, 2d raycast can't cast to hit.. an empty space
I wonder if you could hide this behavior by using what we'd call a "visitor pattern"
Very very loosely
SetNull();
RunUserCode();
SetDefaults();
i mean, it could work if you just make your "empty" tile have a collider and bucket that in? i don't think that'd be a particularly good solution
You do some setup, then call their function, then replace nulls with default values as needed
If the distance from the startPos to hit.point is larger than 0, then there is an empty tile in-between
also so we're on the same page; what do you mean by "closest"?
euclidean or taxicab or some other metric? does it account for walls, that kind of stuff
also #archived-code-general message
All I do is take a rectangle which is the boundary of my garden, my tilemap class produces a basic array of tiles static Tile[,] _tiles;
ok but what if it's like, start position | filled tile | empty tile
then it'd just get the first filled tile
Assume the offset (1, 1), on both axes, is as close as (1, 0) and (0, 1)
ah so like, king moves. i forget what that's called
Raycast can return multiple tiles
so you're just gonna count the results?
Supposedly? It this is more efficient than enumerating through the tiles
i don't think that'd really work for far cases, you'd have to cast infinitely far
and you'd have to add more raycasts to account for diagonals
Yes, and e.g. 2 tiles to top and 1 to left from the starting position won't be detected
looping is far more efficient for this
looping would just be accessing stuff, no need to check colliders and allocate space to report collisions
That is pretty much what I'm doing right now, look at my original message.
Instead of the method being called SetNull(), it's called ResetToDefault(), and instead of RunUserCode, I load json data, and then lastly, instead of SetDefaults(), I run Load() that takes care of post json load stuff.
I guess I don't see the problem, then. What is user-unfriendly here?
I'm more than a little confused
I am just constantly wondering how efficient the raycasts are
they're physics-based, so compared to algorithms, not very
Can you not simply raycast to find the position on a plane, then use that position to look up which tile in the grid exists at that spot?
find the position
of what exactly
the tricky thing is that you're looking for a hole in the tilemap...
That values such as int, float etc. can be set to their default values like this:
void ResetToDefault()
{
someInt = defaultInt;
}
Whilst custom data types require the following approach:
void Load()
{
someData ??= defaultData;
}
void ResetToDefault()
{
someData = null;
}
that's what I've been saying the entire time :/
The tricky thing is that these holes shouldn't be shifted on a single axis from the starting position. Not just diagonally, the offset can be (2, 5), so that the tiles are not detected with a line Raycast
That is necessary if you want to be able to distinguish between a partially-specified value and a totally unspecified value
if the tilemap exists on the floor, all you need is a Plane and you can raycast it without any collider nonsense
the goal is to locate an empty spot in the tilemap
this sounds more relevant for clicking on the tilemap
hole as in no tile exists at that location?
yes, I understand that now, I was just hoping that there is a way to make it cleaner, if not that's still fine, I'll take care of it by writing good docs that explain it, thanks
yes
The goal is to find the nearest position, where there is no tile, inside of the Tilemap, starting from the specified position
note that "inside of the Tilemap" is ill-defined
well there is a bounds
You'll need to either use its current cell bounds (a rectangle that includes all of its cells) or provide bounds
How can you possibly misunderstand it?
you can always add more stuff outside
What do you mean by adding stuff outside?
@gray mural also please answer this
how would you handle multiple possible results
According to my suggested answer, we just check clockwise from the specified position, which might be top left
I need the first found tile. It is returned as soon as found
in the first case, it's pretty obvious what you mean by "inside", but what about the second case?
"inside of the tilemap" is kind of a tautology on its own. a tilemap is its own universe, everything's in the tilemap
but that's not super useful, so there's a bounds that defines the "inside" where tiles exist
but nothing's stopping you from putting stuff outside of those bounds
so you can have stuff inside the tilemap, outside of the tilemap
This is what I would do, yes
at least, if I expect for the empty spaces to be pretty common
if they are very rare, then I would want to store the empty tiles in a collection (ideally something that handles spatial queries well)
What I suppose, tilemap has tiles inside of it, so I don't assume that the tile, surrounded by the other tiles, has to be found
i don't understand this statement
They are common, yes, 3 would be a big distance from the starting position
I suppose that tilemap contains tiles, meaning these tiles are inside of it. So by saying "an empty tile inside of the tilemap" I mean the tile, which belongs specifically to the tilemap being discussed
There are infinitely many "empty tiles" in a tilemap
unless you have an actual tile type for "empty space"
and anywhere that doesn't have a tile is out of bounds
I suppose, it still has a maximum size, but I have mentioned the nearest empty space to the specified position
Gotcha. In that case, just iterate over larger and larger rings until you find a spot with no tile
If you need to keep it in bounds, filter out cells that aren't inside of a BoundsInt
it might be reasonable to limit your search to the bounds of the tilemap
not if you want to be able to place tiles that expand the bounds!
The nearest empty space to the water tile is to its upper-left
... i did say "might"
https://github.com/isadorasophia/murder/blob/main/src/Murder/Core/Grid/Map.cs#L74 you'd need to rewrite it so it works with all the Unity classes, but this function may be helpful
basically creates a line from A to B, if a tile intersects anywhere on that line, you know the line aims towards a tile
I just wanted to say:
If the non-empty tiles are definitely covered by the bounds, then, assuming the previously suggested algorithm is used, you will never have to go more than 1 tile further from the bounds to find an empty tile, which is only the case if the entire tilemap is covered with them. Then you won't have to limit the search to the bounds, since it is certain that the tile is found once increasing the searched rectangle's size to exceed the bounds by 1.
The thing is that the bounds' shape doesn't certainly match the search's, so it is definitely wise to limit the search.
We've previously discussed that the line from the starting position isn't definitely straight
Then I will proceed with this idea, and I thank you all so much for your help!
Hey all, I'm a little lost as to why my Unity consistently crashes while this script runs (I have tested and can confirm this is causing the crash)
while (player.Inventory.isMovingitem)
{
player.Inventory.itemCursor.transform.position = Input.mousePosition;
}
It's simply a boolean while statement, which moves a gameobject to the mouse's position, however it guarantees my UnityEngine will indefinitely stop responding, I've checked Unity's Editor logs and it shows nothing out of the ordinary. Is this a bug or something I'm missing?
because nothing is changing player.Inventory.isMovingitem ?
Why would it ever stop running?
Ah, that's my bad. I had wrongly assumed you could use a while statement identically to an if statement, why doesn't this just throw an error instead of crashing Unity?
infinite loop, maybe you actually meant to do it
Why would it throw an error?
(:
I see, I appreciate the help. My assumption that the while statement would work as an if statement until the bool was false. However, I now regretfully realize an if statement does exactly that haha.
Well, yes, it does run until the thing you give it becomes false
(which is the problem)
An if statement placed in an Update method (so that it gets executed once per frame by Unity) sounds reasonable
Usually when I've accidentally caused an infinite loop it'll throw a memory overflow error or something and stop the game before crashing.
That'd happen if you caused infinite receursion
you run out of space on the stack and an exception throws
Ahh, I see!
(or Unity instantly dies, on macOS)
💥
An infinite loop doesn't consume any extra resources per iteration
Hello
I have a problem with DiscordSDK
This code throws error: Tuple must contain two elements
I can't even run a game
how do i make my game have a resizable window at set aspect ratios?
This is probably a syntax problem; I don't see anything involving tuples at all there
Can you share the entire script in a single paste? Use one of these sites !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.
📃 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.
What should I do in this situation?
this is not what i am looking for. by resizable, i mean being able to manually stretch the window with this setting.
my problem is that i don't want you to be able to stretch the game to ratios outside of 4:3 and 16:9
is that a thing unity can do?
Oh, so you mean stretching it to an unsupported aspect ratio would cause black backs around the screen? I may be wrong but I think you can do that by hooking up a render texture with a black background.
Nah I just don't want you to be able to stretch the screen like this lol
i want you to be able to stretch the screen but not change the aspect ratio
I have a question, If I were to write a boids algorithm wouldn't that be a poor "pathfinding" algorithm as well? I say this because the boids have 3 rules to make them act like birds "Separation, alignment and cohesion" as Sebastian Lague calls it, but with these 3 rules they have obstacle avoidance and the ability to steer to a desired point in a 3D space. Would this produce some sort of pathfinding effect if you make all of them steer towards a point in 3D space? (Of course A* would be a better pathfinding algorithm, just curious)
If you mean the inner camera view then: https://gamedesigntheory.blogspot.com/2010/09/controlling-aspect-ratio-in-unity.html
If you mean the keep the window itself as the aspect ratio: https://github.com/DenchiSoft/UnityAspectRatioController (I actually just found this, pretty cool, seems to do both!)
Im going to take a guess and assume it probably wont be very effective without also adding in a "scoring" system as A* does, otherwise while your birds may be able to avoid hitting eachother and getting around things, it probably couldnt follow the middle of a shortest path without basically skidding walls and other surfaces to get around things, but I also dont fully understand the exact algorithm your using on a mathematical level and how it sees the environment, so thats just a untested guess
Boids would be a great choice for pathfinding in a world with small, infrequent obstacles that you can usually just slide past
Each boid only looks at its immediate vicinity
So the algorithm will fall apart if an obstacle is too big to scoot around
The point of algorithms like Djikstra's and A* (the cooler Djikstra's) is that you can find the best solution no matter how bad the obstacles are
(assuming it's possible to get to the destination at all)
I've implemented Djikstra's for one of my game's system. Then I did A* for another...but the heuristic is currently return 0, so it's basically Djikstra's
😉
Yeah the normal pathfinding algorithm such as A* is better for pathfinding in general but I was just curious if the boids algorithm could "pathfind" even if it wasn't the greatest at it
Maybe if you had a target position boids move to, and you move the target along the best path to the goal...but that's just DjIkstra with extra steps
You guys think it looks okay for a first game? Its for a "fun" class at school
That looks neat!
Trying my best haha. Imma need to add my character ennemies. Hope i dont fuck everything up
are you?
well just tell me what you are trying to code as i know java c# and c++ also html
Horizontal movement
Well i never coded that before but i'll try
Also need jump x)
well i dont know if this will work but at least try it and if it does not work tell me and i'll improve it
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 5f;
public float sprintSpeed = 10f;
public float jumpForce = 5f;
public KeyCode leftKey = KeyCode.A;
public KeyCode rightKey = KeyCode.D;
public KeyCode jumpKey = KeyCode.Space;
public KeyCode sprintKey = KeyCode.LeftShift;
private Rigidbody2D rb;
private bool isGrounded = true;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
float move = 0f;
if (Input.GetKey(leftKey))
{
move = -1f;
}
else if (Input.GetKey(rightKey))
{
move = 1f;
}
float currentSpeed = Input.GetKey(sprintKey) ? sprintSpeed : moveSpeed;
transform.position += new Vector3(move, 0, 0) * currentSpeed * Time.deltaTime;
if (isGrounded && Input.GetKeyDown(jumpKey))
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
isGrounded = false;
}
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
isGrounded = true;
}
}
}
Create a new C# script in Unity and name it PlayerMovement.
Copy and paste the above code into the script.
Attach the PlayerMovement script to the GameObject you want to move.
Make sure your GameObject has a Rigidbody2D component and a collider (e.g., BoxCollider2D).
Ensure that your ground objects have the "Ground" tag for the jumping logic to work.
Holy shit it worked thx so much
No problem if you need anymore help with script's just ask me
Good
I enjoy helping people
Snuffer i have another question for ya
What's up
let me inspect
no im inspecting the errors
Oh okay
Alright so
im listening👀
Ensure Rigidbody2D is Assigned: Make sure your GameObject has a Rigidbody2D component attached. This is referenced in your script by rb.
Initialize Rigidbody2D in Start(): Double-check that rb is being correctly initialized in the Start method.
Here's a revised snippet to verify the initialization:
void Start()
{
rb = GetComponent<Rigidbody2D>();
if (rb == null)
{
Debug.LogError("Rigidbody2D component not found on " + gameObject.name);
}
}
Verify Collider for Ground Detection: Ensure that the ground objects have the tag "Ground" for the collision detection to work correctly. Also, ensure your player has a collider (like BoxCollider2D) attached.
Check for Null References in MovePlayer Method: If the error persists in the MovePlayer method, make sure any objects or components accessed there are properly assigned and not null.
That should fix
if not then I will do hour's of research
thats alot for my smoll brain man
Could you share the specific part of your code where the error occurs?
So I can pinpoint the error
in the script you gave, theres no error, it says its all good. when i try to start the game and linking my rig to my scrip it says that
So basically there are no problems it's just bugging out?
Well then if i were you i wouldn't worry about it
But do you want more flexible movement like dashing and crouching?
I need crouch, horizontal and a high jump
But like rn i cant even play it cause of errors 😦
What do you mean by horizontal ?
Right, left
Oh
Right with " D" left with "A" jump with W and crouch S
Sprinting?
No need
kk
Oh
Late to class feature?
Try this
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 5f;
public float crouchSpeed = 2.5f;
public float jumpForce = 10f;
private Rigidbody2D rb;
private bool isGrounded = true;
private bool isCrouching = false;
void Start()
{
rb = GetComponent<Rigidbody2D>();
if (rb == null)
{
Debug.LogError("Rigidbody2D component not found on " + gameObject.name);
}
}
void Update()
{
float move = 0f;
if (Input.GetKey(KeyCode.A))
{
move = -1f;
}
else if (Input.GetKey(KeyCode.D))
{
move = 1f;
}
if (Input.GetKey(KeyCode.S))
{
isCrouching = true;
}
else
{
isCrouching = false;
}
float currentSpeed = isCrouching ? crouchSpeed : moveSpeed;
transform.position += new Vector3(move, 0, 0) * currentSpeed * Time.deltaTime;
if (isGrounded && Input.GetKeyDown(KeyCode.W))
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
isGrounded = false;
}
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
isGrounded = true;
}
}
}
I'll improve it so it works
Did u put jump on W?
Oh yeah it work for crouch
I just dont have the animation yet
Whoopd
Make sure your ground objects in Unity are tagged with "Ground.
How do i do that
Select your ground objects in the Hierarchy.
In the Inspector, go to the Tag dropdown at the top.
Select Add Tag... if "Ground" is not listed and add a new tag named "Ground."
Assign this "Ground" tag to your ground objects.
But jump doesnt work
will fix
Updated version:
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 5f;
public float crouchSpeed = 2.5f;
public float jumpForce = 10f;
private Rigidbody2D rb;
private bool isGrounded = true;
private bool isCrouching = false;
void Start()
{
rb = GetComponent<Rigidbody2D>();
if (rb == null)
{
Debug.LogError("Rigidbody2D component not found on " + gameObject.name);
}
}
void Update()
{
float move = 0f;
if (Input.GetKey(KeyCode.A))
{
move = -1f;
}
else if (Input.GetKey(KeyCode.D))
{
move = 1f;
}
if (Input.GetKey(KeyCode.S))
{
isCrouching = true;
}
else
{
isCrouching = false;
}
float currentSpeed = isCrouching ? crouchSpeed : moveSpeed;
transform.position += new Vector3(move, 0, 0) * currentSpeed * Time.deltaTime;
if (isGrounded && Input.GetKeyDown(KeyCode.W))
{
Debug.Log("Jumping");
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
isGrounded = false;
}
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
isGrounded = true;
}
}
}
I can only jump 1 time and then i cant
And i dont see tag dropdown, my platforms is from a tile sheet
It shows the error of ground but like it doesnt have an inpact on my movement
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 5f;
public float crouchSpeed = 2.5f;
public float jumpForce = 10f;
private Rigidbody2D rb;
private bool isGrounded = true;
private bool isCrouching = false;
void Start()
{
rb = GetComponent<Rigidbody2D>();
if (rb == null)
{
Debug.LogError("Rigidbody2D component not found on " + gameObject.name);
}
}
void Update()
{
float move = 0f;
if (Input.GetKey(KeyCode.A))
{
move = -1f;
}
else if (Input.GetKey(KeyCode.D))
{
move = 1f;
}
if (Input.GetKey(KeyCode.S))
{
isCrouching = true;
}
else
{
isCrouching = false;
}
float currentSpeed = isCrouching ? crouchSpeed : moveSpeed;
transform.position += new Vector3(move, 0, 0) * currentSpeed * Time.deltaTime;
if (isGrounded && Input.GetKeyDown(KeyCode.W))
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
isGrounded = false;
}
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
isGrounded = true;
}
}
}
Still only able to jump 1 time
Alr bro let me lock in
Is it because ground is not defined ? So it doesnt think im touching the ground
To jump again
I believe so here are some fixes (maybe)
Check for Colliders: Ensure that your ground objects have colliders (like BoxCollider2D) so they can collide with the player.
Verify Collider Settings: Make sure your player's collider (e.g., BoxCollider2D) is set up correctly and positioned to detect collisions with the ground.
Once these steps are done, the OnCollisionEnter2D method should correctly detect collisions with ground objects and reset the isGrounded flag. This will allow the player to jump again after landing.
Here's the relevant part of the script again for reference:
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
isGrounded = true;
}
}
Are you down to do a call? Would be more simple
no point considering my mic is broken but even if it wasn't my voice is still ass
So in my tile map i have colliders, do i need to add one?
I have no colliders *
Nvm i do have one
what all do you do?
as in unity
Rn, i have platforms, tile map collider 2d, rigidbody 2d for my character and also a box colider 2d
And thats it lol
lol i meant like do you animate script model build or what?
Im not sure to understand what you want me to say
Can you animate
No idk how to anything
oh
ITS MY FIRST GAME LOL
Oh i forgot
It looks like you an experienced unity user
although i mostly use unreal engine
Dont use this script (use at your own risk)
Features included:
WASD movement
Mouse look with camera rotation
Jumping when not in flight mode
Press F to toggle flight mode
In flight mode:
Space to fly up
Left Shift to fly down
WASD for directional movement
Smooth transitions between walking and flying
i dont need flying and i cant move
well i did say try at your own risk
help im making an fps game and my character isnt jumping
im lost with troubleshooting
Hi! does anyone know if there are any known issues with playing a video asset on windows?
I'm getting the most generic error: VideoPlayer cannot play clip : Assets/Videos/SkillPlaceholder.mp4 < this is the asset path
(Also not sure if this is the right chat channel on this discord, lmk if there is a better one)
- It works perfectly in unity editor on the same machine, the issue is only in builds.
- it's IL2CPP on windows.
- Tried transcoding options, h264/vp8 < all work in editor as well.
- Tried disabling engine stripping / lowest stripping levels.
- Tried loading via URL and confirmed URL is correct, same error as when using a video as asset.
- Tried preparing and calling play on prepare callback
- Audio output mode is none, it's a single video track video only
- Version is Unity 6000.0.29
what have you done to debug so far
are you receiving the input? checking for grounded correcty? etc
try #🔀┃art-asset-workflow maybe?
ive used Debug.Log to identify when the jump input happens
it appears that my character is constantly jumping
you wanna show the code you're using to make the jump happen?
alr 1 sec
my code is too long to be pasted in here
it says I need nitro
i can try messaging in segments
alr
!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.
private void Jump()
{
// reset y velocity
rb.velocity = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
rb.AddForce(transform.up * jumpForce, ForceMode.Impulse);
}
private void ResetJump()
{
readyToJump = true;
}
}
this is to apply the force
and how are you calling Jump?
'''cs if (Input.GetKey(jumpKey) && readyToJump && grounded)
{
readyToJump = false;
Jump();
Invoke(nameof(ResetJump), jumpCooldown);
please format your code like the embed shows above
so have you debugged to see if Jump is being called, and if it isn't, check if Input.GetKey(jumpKey), readyToJump, and grounded are as you expect
yes I have
mb for late reply
Debug.Log(readyToJump);
//when to jump
if (Input.GetKey(jumpKey) && readyToJump && grounded)
{
readyToJump = false;
Jump();
Invoke(nameof(ResetJump), jumpCooldown);
}
alr
Delete this paste Start a new paste with this content
Debug.Log(readyToJump);
//when to jump
if (Input.GetKey(jumpKey) && readyToJump && grounded)
{
readyToJump = false;
Jump();
Invoke(nameof(ResetJump), jumpCooldown);
}
it shows that the jump is happening however im not pressing the space bar
can you show me an example of a formatted msg if ok, sry im a bit new to this stuff
what have you set your jumpKey to
Not quotation marks.
I wanna implement velocity to unity starter third person controller asset, for pushing player to spesific directions. What is the right way?
spacebar
should just be space
Hi, im trying to create an easy way to save and retrieve skill data between game sessions.
My go to is to use a Dictionary<string, int> (i just need to store the level of the skill, hence using integer).
for saving that string into the dictionary im thinking of 2 options:
right now im using set of enums so i can just access to the desired skill with MyEnum.SkillName but (and it sounds stupid) i need to cast it to string every time.
I would like to use a set of string constants and create my Editor class to chose from a dropdown menu just like the enum in the inspector but i dont know which use case is better
If you're willing to not use strings, you could cast the enum to an int as it's key.. but then again you probably wouldn't need the dictionary and simply just use a list or array instead.
for clarity i would like to see the names of the skills in my saved json (and for statistic maybe in future)
is a readonly string[] in a static class good option?
Well, needing a static class is quite a big concern by itself - moreso than the read only attribute. Read only would be relative to what you're explicitly trying to do.
hi, I'm trying to create a spaceship driving simulator and I don't really know how to move it without it stopping when you release the key (I want it to have a variable to create 'drag' whenever it's getting close to a planet later) but I don't really know how to do it. Can someone help me ?
basically i have a scriptable object that holds info about the skills like name title description to show to the player.
I need to save the level of this skill (so an id with an int) and i also need to retrieve it when the you open the game again.
im trying to find an easy way to create a reference to these scriptable objects when i load back the game, aswell as for when i save it
since they are already in the hierarchy once the scene load i just need to put the levels in there
thats why i need to retrieve them from a dictionary(?) with the given ids (and i wanted to use simple string,int dictionary)
also i need to be able to access to these skills from parts of my game. for example if i want the level of the FireBall at a given point i wanna be able to access to it doing myAbilityDict["fireball"] and thats why i was using enums
and you're not using a dict<enum, int> because?
because i have many skills and many different enums, i dont want to hold all the skill names for different categories in one huge enum
haha, fair, that'd be my reason against it too 😄
so im using string for the dict but now i need to cast the enums to string. i guess its the best option
so, you define the skills and their IDs in SOs?
i just made an editor script that gets all the Enum names from the different enum categories ive made and lets me pick one from it and put it as string into a scriptable object
so i have one scriptable object for the skill that contains a string which will be the id of the dictionary
and in future i can access to it by just doing myDict[category1.skillname]
sometime editor scripting saves you many thinking
I wonder how to program potentiometers for Unity.
the same way you do it with any other app. Read the values, map values to specific functions etc.
Alright, then I'll have to build the box for the guns, solder the arcade buttons to a keyboard circuit board.
that or use a microcontroller
Is this what you mean?
https://discussions.unity.com/t/using-unity-3d-with-arduino-micro-controllers/622361
those are controllers too yes, those are specific to multiple input reading
if you said potentiometers then you would probably need a different controller like Arduino or Pi
What I bought is a non-ghosting keyboard. My idea is to connect four player sets of buttons and joysticks. The guns are a separate thing with a USB connector.
So I hope that means that half of the work is done for me.
Yes, I was just watching something about potentiometers on YouTube controlling a Unity gameObject's spin. But I wonder how I'm going to code it.
Probably like the controller. Something about -1 to 0 to +1.
Okay, I found this. Will check it out. Thank you very much for your input.
https://www.youtube.com/watch?v=jOSL6fjugGs
its pretty much that easy. I don't like that they use a paid asset though , its easy to abstract arduino/communication via usb using Unity
Alright, this whole thing is challenging, with multidiscipline skills required. But I've made it this far.
ah yes If you use micro controller, you need a very basic knowledge of their native lang.
I use arduino and esp32 so I mainly use C/C++
you don't have to abstract to much on that side of the coding though, you really don't even need to read it from there you could just run the Serial port and do everything from that in .net
Does anyone know why ClosestPointOnBounds and ClosestPoint are just so horrendously inaccurate
I'm feeding it the world position of my hand and sometimes it will just return a position identical to the hand's position and sometimes it will provide a somewhat accurate position
It's never actually returning a good position
Do I need to convert it to local space or something
Nvm ClosestPoint works but ClosestPointOnBounds doesn't I think I might've been doing something wrong
running into issues with buttons and serializations
I have an error message that I don't understand, can someone explain " plasticSCM/Unity.plastic.Antlr3.Runtime.dll is missing " please ?
basically i have this extremely simple public void statement which changes the text of a given objects with two different things to serialize, a string and the TMP_text object i want to change this on
{
textasset.text = text;
}```
however this does not show up when i attempt to select this function to execute as a button onClick function
i suspect it has to do with attempting to get two different types of variables, a string and TMP_text asset
most likely because it doesn't support those parameters let alone 2
while i could plug one of these parameters at the top of my script i do wanna keep this modular
seems like you might have a fundamental misunderstanding how this supposed to work
if you want something modular you should use an actual script to do so
In a professional team , do team members have to use the same Unity version ? Like I use Unity 6 but my mate use Unity 5 , will that be ok ?
if you're working on the same game, no, that's gonna cause issues
definitely with major versions
most definitely not, Unity 5 and 6 are so far apart as to be on different planets. Always use the same version
with minor versions, you might get away with it? but it'd still be super unreliable
just use the same version
Do most developers switch to Unity 6 in companies nowaday or they still use Unity 5 ?
Very few people indeed still use Unity 5
you do realize there is Unity 2017,2018,2019, 2020, 2021 and 2022 between Unity 5 and 6
whats a good way to tie a class to a gobject
need a "map" holder to store refs to random shit (start point, diff parts of the map, goal collider) and i dont want to give it a whole monobehavior
our coolg uses 2019
And I need to know that why? Even if I knew what 'coolg' is supposed to mean it's irrelevant. Do not ping random people
wrong answer <@&502884371011731486>
@fiery elm Don't insult people or ping them randomly. Read #📖┃code-of-conduct
What do you mean tie a class to a gameObject ?
- do people still use unity 5
basically no one
"our college still does"
and i need to know that why?
but meh sure
rn my structure is a gameobject that stores different parts of the map under it
borders, the floor, start and end point
Versions go in this order 5 2017 2018 2019 2020 2021 2022 2023 6
am additionally storing these in a Map class for easy access (and because apparently retrieving these through obj children is bad) but thats obviously clunky
So what is your question really ?
is there a way i can tie one to the other
because right now i cant exactly assign to Map's vars without a lot of hacks
Are you asking how to put the right reference in start_point for example ?
sure
Easiest way is to make Map a mono why don’t you want that ?
i mean i assume i can do some all_objects (or whatever) .GetChild("map")[0].GetChild() etc etc
cuz its just a data holder
slapping random baggage on top (which i assume thats doing) feels like the wrong approach
It really is not
idk if it is
h m
ama peek what mono is exactly cuz im used to class inheritance == equip the class with all hte baggage of the parent
yeah from a briref look this doesnt seem needed
its not a script its just a class
All scripts are clases
and not all classes are scripts yeah
Inheriting from Mono would allow you to easily reference other objects from the hierarchy
Otherwise you need to first get the references somehow, pass them to the constructor of the map class and then have that map instance be used where you would like it
You could use something https://docs.unity3d.com/6000.0/Documentation/ScriptReference/RuntimeInitializeOnLoadMethodAttribute.html to hook in and make your map instance but that is not the Unity way so to speak
There is nothing wrong with having a lets say singleton monobehaviour that holds important data for your level
a script is a text file
you may be thinking of "component" here