#archived-code-general
1 messages · Page 440 of 1
thats doesnt even use the same method they're asking about..
i meant in reference to how the DeltaTime
i have to change my profile pic????????
i got message
fk yall
monsters
devils
my hentai pic:((
<@&502884371011731486> they're still spamming
No, the racism from your profile you idiot.
look in her holes. its deep man
ok.
oh
You have to be 13 to use Discord.
thanks god
Anyway, just going to ban you anyway. See ya.
pour one out
!ban save 1245773585436377210 Spam. Racism.
imnotdifferent. was banned.
that was... bizarre to say the least
frigging kids just have no idea how to do anything themselves anymore
fictional character lol
like actually bloody helpless
One thing Id suggest is also just printing out the velocity and seeing how it changes over time too. Maybe along with the current time
@safe fable @shadow wagon @dense pasture theres nothing you need to say about it. really just move on. most of the conversation above shouldve been avoided
ironic that as the amount of learning resources became more available, the decline of people figuring stuff out, has crept more
thats even more mind blowing
when i got into coding i had to beg my mom to get me all these 50lb books on C and BASIC
and thats the only way you had to learn it
trial and error
So, this isn't normal? What the hell. I'm not doing anything special.
like all the resources we got available today are insane
forcing yourself to learn like that is amazing though. I wish i didn't have chatgpt and the internet at times. (great if used correctly) but the temptation is crazy bad yk
if you dont understand it, yeah dont use ai.
if you've been doing this for almost 30 years, i'm just tired of rewriting all the boilerplate crap
If you all want to DM each other then go ahead, but again theres no off topic in the channels. This is seriously just spam and it's really hard to help the person actually asking for help!
sorry you're right
also before when barely anyone was making gamedev resources, or online knowledge was limited, that was basically a forced "yall gonna have to figure this all out yourself"
ive been saying this for over 10 minutes.
wait, its code-general not code-help channel. we can talk about general code stuff here >.<
(they're real sticklers about categorizing your discussions)
unity discord members when somebody strays from the channel topic for 0.0001 seconds
Actually a fair point the channel name is a little unideal
I mean I don't see the other context around your code, so I can't say anything other than print it out.
now theres a million tutorials for making an inventory and because you have to gamify youtube that means the most low tier garabge "illusion of being educational" tutorials are everywhere
and yet your problem was spammed away, meaning no one is helping. 🤷♂️
im sure the talks about someone learning code 30 years ago with C and BASIC are very unity related. Either way, go DM each other if you want to continue
Gotta keep in mind people like Bawsi have been offering their time and knowledge to people of all backgrounds and experience for as long as I remember. People are strict here because this place is the amazing equivalent to a tutorial mcdonalds powered by volunteers. There’s a process to concise and efficient support
tutorial mcdonalds 😆
Here is the issue more clearly
okay man, its not that deep but i got your point.
It’s not a discord power tripping thing it’s just a respect to the insane amount of volunteered support taking place
kid came in and disrupted that himself lol
anyway, its over. back to work! all of you
honestly its hard to tell what im looking at, I meant it more as debug and see for yourself what the values were over time. Ideally just move in 1 direction too so the vector is easy to read (or print out the magnitude).
You'd still need to share the context surrounding the one line you pasted. Theres a lot more than just calling Smoothdamp, like how are you even using that Velocity
one thing that was concerning was the walk speed being 0.01 also
Plus there were so many messages between the beginning and now I can barely find the other messages
If it's anything above 0.01 the character zooms off. No idea why this is the case.
well just assigning the velocity vector doesnt move the character in the first place. share the whole relevant code
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
they did it correctly
discord just puts posts over 2000 chars into a message.txt
if only the code command had a section, as the 2nd line, about "📃 Large Code Blocks"
oh yeah, ignore me 😆
is there a reason also you're using Smoothdamp here on the velocity anyways? Id really just use MoveTowards here, as I suggested the other day
you are moving by velocity every frame also cc.Move(velocity); rather than every second so you should use Time.deltaTime. This is what i meant when i said "Theres a lot more than just calling Smoothdamp, like how are you even using that Velocity"
that is why your walk speed is currently very low
anyone here have any experience with using Steamworks.NET?
Its not a big issue (yet) but for some reason when I play my game, steam will not recongnize when i close the game and always keep it running. (or rather say its running), until i close it in task manager.
fixed the console issue btw @somber nacelle 😄
it was just a bunch of anchor issues and transform issues ... just tideous stuff
also i do make sure run in background is disabled
yeah that's expected when playing the game in the editor because steam won't recognize that the game is closed until the entire process is killed. since the editor started the game steam thinks that the editor process is the game
@somber nacelle sorry i should have worded myself better. it persists even when its standalone
or do you mean that the actual build is still running? because that is something else entirely most likely
yeah unforuntately the actual build it still happens
if you're certain it is related to steamworks.net then find their support channels and get help with it there
fyi do not disable this option for multiplayer games as if you tab out bye bye connection (rust used to do this)
oooooooooooo thanks for that
it could be different now but I just remember it having issues many years ago.
guess you will find out pretty quickly if it impacts other things
im testing it now 😄
i presume its only the main thread updating that is "paused"
everytime i alt tab and idle for a bit my character disconnects from the server
so we'll see
@steady bobcat yeah that actually just fixed an issue that i was having that i blew off. I thought it was something to do with photon fusion causing a disconnect after a certain amount of inactivity
turns out that was the issue
you fixed a problem for me i didn't even ask 🥲 ❤️
haha glad to have helped
so i've gotta ask, how am i supposed to get around the C# reflection cache exactly if i'm using reflection to find and construct serializers/converters? it seems silly that I can't disable the cache
i can't seem to find any information on why this is done in the first place
Mono and IL2CPP internally cache all C# reflection (System.Reflection) objects and by design, Unity doesn’t garbage collect them.
0 explanation for why this is by design
ah, buried in the bowels of google
Could someone help me? I've been beating my head against the wall trying to get some udon# scripts to work but I can't seem to
Like it won't turn the script into the udon#
!vrchat
Join the growing VRChat community as you explore, play, and create the future of social VR! https://discord.com/invite/vrchat
you'll find the most VRChat expertise here^
alright, thanks man
is creating meshes instead of tilemaps in unity possible?
tag me if someone has an answer
I will tag you to say you need to use the proper channel for these type of questions
Or use #💻┃unity-talk
I've heard instantiating 2 or more assets at the same time can make the game stutter
is Unity that sensitive to asset instantiation?
You've heard a blanket statement which makes no sense. You should try it and see. Unity isnt "sensitive" to anything here, if you have a very large assets then of course itll take longer to spawn compared to something simple.
Which can be fixed by itself by implementing some simple asynchronous delegation
We have built in async Instansiate now
@west lotus So spawning 1m elements won’t spike?
It takes resources to instantiate or destroy objects. But that isn't a sensitivity issue on Unity's side but more of a fact of how things work. It will take resources on your PC to open any program, or create any file.
It's also important to understand what a "stutter" is. Your game's smoothness relies on the application updating constantly. Each update cycle is called a "frame." That's where fps, or frames per second, come into play.
Movies are normally shot at 24fps, TV shows at 30, and fast moving competitive games at 60+.
A stutter is when a frame takes longer than it should to process and the average fps drops because of it.
So yes, you can cause a stutter by instantiating or destroying too many objects within the same frame. But there are tons of techniques to handle that.
Spawning or destroying any element would create a spike if you aren't doing it every frame. That's because a spike is just a peak over the average.
Using ASYNC is a technique to allow the main thread to continue while the object is being destroyed
They mentioned built in async, makes me wonder
I remember seeing it in a game dev tips from a channel who does a ton of shorts about it
Something something async is not always using other threads
Unity's Async is not multi-threading, yes
plain c# async is also not inherently multithreading
Depends on how you do it. Spawn 50 a frame probably no. Spawn 200k yes.
well, I'll certainly have to come up with something to smoothen instance creation, since rooms may have like 50 enemies in it all occasionally instancing projectiles
Projectiles should be pooled
Makes sense.. async but instantiation still has to complete within the frame
pooled?
Google object pooling
No async doesn't complete within the frame unless you aren't using Await
yes, I can do that to many such cases
They mentioned built in async instantiate
I can't postpone instantiation because my game has to be frame perfect
but I can pull other tricks
They are talking about the built-in async instantiate
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Object.InstantiateAsync.html
Damn, thanks for clearing it up. I was thinking they meant the standard instantiate method’s under-the-hoods got replaced by an async impl
The best thing to remember here is that the creators are always just saying stuff for views. Either they're saying something so completely obvious, or something so completely wrong when you look into any details.
alr thanks lol
that makes sense
I mean, it did the short to teach what object pooling is
the enemy in question threw 8 projectiles in a single blow
perhaps I just phrased it badly
8 projectiles probably shouldnt stutter in the first place, but do yourself a favor and just look at the docs for unitys object pool. It's very easy to implement
I see
thanks there
Well yeah so I didn't clarify on what to do specifically because of that. You can do the process asynchronously if you can afford doing it, but it's not as simple as spawning a background thread. You can also use some other asynchronous methods. Maybe even introduce pooling.
I wanna see the game engine (or operating system for that matter) that doesn't spike when you perform an extremely expensive operation.
I'm trying to implement accelerometer for my 3d bounce ball game. I can't seem to move much in horizontal direction using accelerometer. Below is my script. I have tried google and chatgpt etc as well but can't seem to resolve this.
a powerful website for storing and sharing text and code snippets. completely free and open source.
The code uses horizontal acceleration as is but adds the vertical acceleration to the existing velocity
I have collectibles using an Event that contains their type (an enum) and position (Vector3), but not every Listener cares about both of those. Is there a way to add a Listener that automatically discards one or both parameters, or do I have to add them to the signature of every function I want to listen to the Event?
just ignore the parameters
is no big deal
unless you make a signature without those
you would have to fire a separate event with a different delegate type.
You can ignore them with the _ discard syntax though
How do I do that?
you write _ instead of the parameter name/type
public void DoStuff(CollectibleType _, Vector3 __)
Like this?
depends on the context. For a regular method, yes.
For a lambda, you don't need the type either
this isnt a discard, its just treated as a variable. https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/discards
truthfully for a method I dont think it makes much sense to write it, if you create the method using autocomplete when subscribing to the event it'll just give it a name anyways
Oh interesting. TIL _ in a regular method is just a variable name.
it does hint I guess that the variable is not used, i dont think ive ever used it in such a way though. It's funny that this is valid
void MyMethod(int _)
{
_ = 5;
}
no more single character variable names, we move onto underscores
It's a regular method. Using the underscore does prevent my compiler from complaining about unused variables, though.
Should be using longer descriptive variable names anyhow, imo
Yeah but if you're literally not using it then _ is a descriptive name
ah I forgot about that. Another workaround to consider, mostly when dealing with more variables, is putting them all in a class. That way you're just subscribing to an event with 1 parameter and all the values are still there, with none of this discard or unused variable issue
Unless the subscribing method doesnt care about any variable at all
Was refering to the
single character variable names
bit
That was most clearly a joke
Went right over my head
hey guys, are we able to upload unity projects to github. Is there any problem with that? only reason im asking is because i know they have their own version control thing but from what i see its like $200/m 😄
But is there any issues with just uploading to github for collab and version control?
i guess im more concered over file sizes and stuff if git supports that
Yes Git is a very popular choice for version control for Unity projects (and every other type of software project)
from what i see its like $200/m
just like GitHub, Unity has a free tier within certain limits.
@leaden ice got it. Surely i would need the LFS thing git offers, since the project is 2+GB?
LFS is about the size of individual files
not the size of the repo
You should use LFS in general, yes.
i see i see
Hey guys, I wanted to know if you think im overthinking what im trying to do. I am trying to make a script that can read a list of components with assigned values (7 components, each with 15 possible values) and create an object out of it (the object is a 'spell', but not really relevant to what im trying to do rn). Each value in the components may also have modifyable 'values', like dimensions for the square value under the shape catagory.
Would the best way to go about doing this be an Interface for each category, with each value being a class(? i dont know what instances of interfaces are called) of the its catagories interface, with the Interface having all the possible modifiable subvalues?
can you give some examples?
yeah, sorry this is kinda hard to explain.
A heat ball spell:
Category - Magic Type: Value - Heat
Category - Target: Value - Projectile
Category - Source: Value - (Character Object)
Category - Shape: Value - Circle: Subvalue - Dimensions: Vector2 (2,2)
Category - Duration: Value - Until Collision
Category - Intent: Value - Projectile: Subvalue - Speed_Intesity_Ratio: Vector2 (30,70)
Category - Cost: Value - Set_Amount: Subvalue - Amount: int 30
each category would have an indiviual interface
each value of that category would have a script under that interface
and the interface would have all the possible subvalues for the main values contained under it
What benefit is having each unique class have its own unique interface?
Ok so this is a rehash of the same sort of problem I have been solving/working on in like 3 different projects - a generic set of attributes for a spell or item or whatever
because each category (eg. shape) will have 15 possible values (eg. circle or Oval), each may share some subvalues but also have their unique ones. Like the circle and the Oval may both have base radius subvalue, but cylinder alone has height
The way I'm doing it in my current project is something like:
public class Spell {
List<Attribute> attributes;
}
public class Attribute {
double _value;
AttributeType type;
}
public enum AttributeType {
MagicType,
Shape,
Duration,
Cost,
// etc...
}
``` source and target wouldn't be part of this object, but maybe some other object that wraps the spell with a source and target for casting.
And I use various encoding schemes with the double value to encode various types of data in it
Here's a snapshot of my Attribute.cs script: https://gist.github.com/jschiff/a8201a5bd62512102a5f301f0abb73de
it works with all these data types: int, float, Vector2, and custom enums
im a bit confused, ill look at the code for a little bit and see if i understand ✅
Later on i might add more stuff to support other types if needed
OK, so you're saying something like this? (Abridged)
public class Shape : Category, IShapeCylinder
{}
public interface IShapeCylinder
{
float Height;
}
more like
public class Circle: IShape
{
float Radius;
}
public class Oval: IShape
{
float Radius;
float Height;
}
public interface IShape
{
float Height;
float Radius;
float Width;
}
I think?
Seems a little odd to have the interface have properties you don't want in all of the classes that use it. Normally an interface is a good way to ensure any class that uses it has all of its properties or methods available.
in fact, you can't not implement an interface's members so that code isn't valid
Yeah this is definitely not a use case for interfaces
Im a bit lost, but to my understanding does it work like -
AttributeType is an enum with each type of attribute
value, vector2value, and other similars would be subvalues for the induvial attributes
?
The only thing that's an enum in that link is AttributeType
oops yeah thats what i meant
For an individual spell or something you would have a List<Attribute>
conceptually just like your example above
Category - Magic Type: Value - Heat
Category - Target: Value - Projectile
Category - Source: Value - (Character Object)
Category - Shape: Value - Circle: Subvalue - Dimensions: Vector2 (2,2)
Category - Duration: Value - Until Collision
Category - Intent: Value - Projectile: Subvalue - Speed_Intesity_Ratio: Vector2 (30,70)
Category - Cost: Value - Set_Amount: Subvalue - Amount: int 30
Each line here would be one attribute
except as I mentiuoned above I don't think Source and Target belong in this list
really it's used in my custom property drawer for this type
Here's an example.
Attributes is an AttributeList, and there are two Attributes in this particular list
It lets me display them properly in the editor
So the Loyalty attribute displays as the Loyalty enum value dropdown.
Hull Integrity displays as an int
return editorDisplayTypes.GetValueOrDefault(type, typeof(double)); // Default to double (for now)
just returns the first instance of a double type in attributes right?
no
it returns the value mapped to type in the Dictionary
and if it doesn't find one, it returns typeof(double)
oh i see
basically just saying double is the default
I haven't shared everything here - there are missing pieces like the AttributeList class and the editor scripts
Just trying to give you a gist for how I'm doing things in this project.
Okay i think i get the idea of it
Essentially it's just a list of tags and values
and I'm just using a little trickery to shove all the different value types into a single double field - but that part isn't even necessary
you could do this same thing by giving attribute several fields like public int intValue, float floatValue, Vector2 vector2Value etc and your code should know based on context which one is appropriate to use for a given tag.
It would waste a bit of memory that way though
thank you for the help! Im gonna give it a try
see #854851968446365696 for what to include when asking for help
hi, just wondering is there any method to run code only if under a specific build profile? like a preprocessor define or something
Build profiles let you define scripting defines
Rider stucks if it haven't updated code, but game is already running. "Don't start game before update" isn't solution, because I don't want after кandom click restart unity
Is there way prewent unity from running if files are updating or another solution?
You can use the included platforms ones such as UNITY_ANDROID or make your own as said already
so in HDRP, with unity lights, if I do Light.type, why is Point the same value as Area(rectangle)?
It means that according to LightType, Rectangle and Point are the exact same(but Disk and Point are NOT)
is it a good standard to impliment a standard system via prefabs? ie if im going to have NPCs in my game have nametags i have a nametag prefab that i toss on each npc? and if im going to have a proximity prompt interact thing (ie press E to interact once within a trigger box) id have that on a prefab too?
Yes it's a good idea to turn objects you're going to reuse a lot into prefabs
also how do i make my game effecient... like if im going to have a decently sized nice quality map id need to optemise it to actually run it, i know this means like model culling and like unrendering but when should i be thinking about that? what should i do as a standard, and should i make scripts to do thoes optimal things from the start?
i know id avoid heavy processes, huge triangle counts, and other unnessicary considerations in final graphics setup and stuff, but like... are there any programming techniques i need to know/avoid?
Asset Streaming might be vital depending on the actual size, device you support and the size of the assets.
whats that?
You can hold only a certain amount of assets in memory.
If you have huge map with a lot of variety, you might easily bust RAM.
Obviously, it depends on what you have for assets.
Low Poly is usually not an issue.
yea however i wouldnt need the entire map to be simulated/rendered at once... so i presume id just pause processees... (processi?) in the far off areas to handle many many assets
Do you know what RAM is ?
Do you understand that each assets take space in RAM.
yes, but if you have a chunk 15x the render distance out you dont need that in ram, so youd unload it.
remove from ram
If you have 1000 textures 4k, but only 200 are actually used in a section of the map, you are wasting resources.
The process of unloading and loading assets is asset streaming.
You cannot simply deactivate it.
ohhh ok
You need to use things like additive scene or/and addressable to handle that.
But again, it is only an issue if you believe you are going to get to that point in term of assets.
i think i will
i plan to have a quite expansive map with some town areas you travel between, so a lot of space will be dedicated to lush expanses with a ton of models scattered around, using lower poly versions at further distances will help ease that, but there still might be thousands of individual models on screen at once
If your map is in space or have 5km+, you might want to use floating origin as well.
That being said, you should try to restrict yourself to something small. Authoring everything would be extremely hard alone.
i can get something rough put together relatively quickly, plus the in between landscape doesnt have to be perfectly refined straight away so im thinking of getting it there and down before making it look nicer
Also mind that the unity editor does not support working on large detailed maps efficiently. It will be a painfully slow experience for authoring.
you can work around that but for a solo project, that wasted effort is virtually never worth it vs spending it on other, more valuable bits of the project.
yea i was thinking of having areas like open feilds or dense forests have the common foliage put in during loading, bcs theyd all be clones anyway so i can just set up a script to place so many randomly within set areas, so my actual workspace map will be much less detailed than what is there during actual play.
if you can’t fit your game into 4km square and avoid streaming that map. You should investigate other engines.
unreal engine is geared towards bigger worlds and does a lot of the optimisation for you. you could replicate the same systems in unity if you know how to
that is all conceptually possible, but doesn’t change the fact that the editor can’t really handle it without you essentially building a custom HLOD system
you can get streaming to work quite easily, but that’s not the same as having a good workflow too.
well ive asked because i wasnt going to have a super super detailed like photorealistic map, but i wanted it to span a long distance
photorealism isn’t even the issue here
i know city skylines is so bad bcs its using something in its graphics that is very heavy in how theyre using it, but i was wondering if i could like have a map that can look nice with a decent level of detail that does span quite a long distance
like if it in runtime handles that
bcs i have methods i could use to circumvent the editor space not liking super high asset numbers, and in runtime asset streaming can remove nearly all the assets to keep the RAM useage low
well... manageable
You can have a huge map if you only want to look at it from far away. It’s all a function of perspective
Asset streaming isn’t a plug and play thing in unity.
i mean like, if i had a forest that you can at a realistic speed walk around in, 1:1 scale, and i wanted an hour long walk in one direction (5 miles) where it is a nice somewhat detailed setting at each moment. that would simply be too many assets for the editor, however if i generate thoes assets and make use of asset streaming to cull the stuff too far away thatd be fine in runtime wouldnt it?
yea thats why im asking to figure out the extent of how much id need to use it
I think you still haven’t fully understood what exactly the critical parameters are
Assuming you don't have a separate asset for each tree, it should be fine. Use techniques like draw call batching, instancing, LODs, Billboards.
Asset streaming purpose is to reduce the memory consumption, but you wouldn't go out of memory with just a forest(assuming your assets are optimized for games).
Just because you have millions of trees doesn't mean that you consume 1 tree worth * million of RAM. That would make most open world games impossible.
You also seem to confuse culling with asset streaming. Culling is preventing objects from rendering. Streaming is loading/unloading them into/out of memory.
Amazing, thank you
https://docs.unity3d.com/6000.0/Documentation/Manual/json-serialization.html
Is the JSON serializer good? According to the manual's own page it's better and faster than "popular json tools" which I assume they mean Newtonsoft as I've heard a couple of horror stories from that. Idea is to serialize most if not all data driven game data into json and read off it at runtime, then probably turn into blob assets
Yes it's good but it has strict limitations on what can be serialized
The objects need to conform to these rules: https://docs.unity3d.com/6000.0/Documentation/Manual/script-serialization-rules.html and it also doesn't support naked lists/arrays.
yea, so for this i would use asset streaming to unload items too far away and handle the ram requirement,
then i would use culling, draw call batching, instancing, LODs, Billboards to reduce strain on the gpu from rendering the scene,
would i need to do anything else to make a scene too large to be simultaneously all loaded actually workable? like do i need to worry about editor limits too much?
im thinking i can have each asset normally be a cube to prevent undue stress in the editor from detailed models, and have scripts turn the models into what's required in the start-up process... should the editor struggle with showing all of the assets
If your editor can’t handle it you probably should consider changing what game you are making
I'd suggest forgetting the asset streaming for a while, test and profile your game as is. Then identify bottlenecks and max memory consumption. Decide if it's within the decided memory budget and move from there.
Because it sounds like you're trying to fix a problem that doesn't exist yet.
Hi guys! Idk if this is the correct spot but I have a question I am trying to create a script where an enemy follows the player around a maze. Does anyone have a good tutorial or reference I can follow?
bake your maze with a navmesh and use agents
Sounds like a question for #💻┃code-beginner or #💻┃unity-talk
But yes, what Mao said.
Thank you guys!!
How do i figure out what names Animation.Play() is expecting?
This is my current setup in editor
OpenOptions/CloseOptions
Yeah
but this is my current setup, and it's saying "OpenOptions" doesnt exist when i callTitleScreen.OpenOptions()
using System;
using UnityEngine;
public class TitleScreen : MonoBehaviour
{
[Header("Parts")]
[SerializeField] private Animation animations;
[Header("State")]
[SerializeField] private bool buttonsFrozen = false;
private void Start()
{
animations = GetComponent<Animation>();
print(animations.GetClipCount());
}
public void QuitGame()
{
if (buttonsFrozen) return;
Application.Quit();
print("Quit game");
}
public void OpenOptions()
{
if (buttonsFrozen) return;
animations.Play("OpenOptions");
}
public void CloseOptions()
{
if (buttonsFrozen) return;
animations.Play("CloseOptions");
}
public void PlayLevel()
{
if (buttonsFrozen) return;
print("Play level");
}
public void FreezeButtons()
{
buttonsFrozen = true;
}
public void UnfreezeButtons()
{
buttonsFrozen = false;
}
}
It does say it has 2 animation clips, but i can't get any more info
are they legacy animationclips?
Animations must be marked as ‘Legacy’ in the Inspector for the animations to be found by this method. This option appears after switching the Inspector Window to ‘Debug’.
new AnimationClips are for Animator, legacy AnimationClips are for Animation
what does switching the inspector to debug mean?
OH
found it
i have never seen this before, alright
is there a way for me to make a custom curved collider? using polygonal works in base, but when scaled up, the vertexs get less and less accurate. im trying to make a cone collider
and using a capsul collider to approximate has the same issues
Only with MeshCollider
by providing a custom mesh.
i see, ill look into it. ty
Hi guys, I've trying to figure out how to use a package called ModTool, but I haven't been able to get it to work whatsoever- I don't really know why and documentations on ModTool is scarce to the extend that I can't find any info...
For the reason in case this becomes an XY question, I've been trying to figure how to add support for additional content (Including code) to my game
Youd have to ask the people who made it or in whatever channels they've made for this asset
Is there a recommended tool for what I want to do? Preferably without having to create whole custom systems?
They only have a thread on discussions.unity.com, 1 outdated tutorial, and a documentation that doesn't explain my issues
The only suggestions I've seen were about using lua which would be more like minecraft cheat mode. If you're trying to let the user add any code at all, it's really just bet to let them figure it out and mod it
It's actually mainly about myself, since I'd like to take a more modular approach to the kind of content that exists, if users wanna mod it why not, but I'd like to be capable of just messing around and spam random stuff, players can include the optional content if they want to
Partially it's also because otherwise I feel restricted when it comes to the "cannon" content
Might be viable to make MonoBehaviours for modded content that reference ScriptableObjects containing Lua code like you suggested (or something similar)... But will prefer to use it as a secondary solution, since I'm pretty sure that it'll still put a lot of restrictions...
Im not really sure what kind of content youd be referring to here. It kinda just sounds like you want to introduce modding, but also be the one modding your own game. This most definitely wont be fun for you
Hey, how do ya'll deal with "double namespaces" in Rider (I suppose it should be similar with just resharper)?
For example, I have an asmdef with the following root namespace: MyCompany.MyGame.Runtime. Then I place a script in the following folder: Assets/Scripts/Runtime/MyScript.cs. Then, Rider complains that namespace MyCompany.MyGame.Runtime is incorrect and should be MyCompany.MyGame.Runtime.Runtime.
I know I can exclude namespace providers/folders via right click and saving this info to .DotSettings, however am curious if there are other ways around this as I don't like to litter my repos with these files.
I don't use rider but I could guess that you can use just one .DotSettings file and provide the full path to the script?
not sure if this is the right place to ask, but my AI boss character spins around like a bey-blade, and also pretty often falls through the floor
i am following a quite long tutorial series -- the boss is using a navmesh agent aswell as a character controller and a rigid body, not sure where to begin with the troubleshooting
The .DotSettings files are created for each .csproj file when you exclude a namespace provider it seems (there are more cases where they are useful tho), I don't think you can have a single file 🤔
The contents of this file don't seem to include any mentions of the asmdef itself
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=assets_005Cscripts_005Ccore/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
The problem is not the files themselves, but that I have too many of them since we use asmdef extensively 😅 This is esp annoying for custom packages, a bit nitpicky but I want clean repos!
In many projects I need some way to permanently store data such as "current gold" or "levels completed". Many objects in different scenes need to access this data. For a long time now, I've been using DataManagers with a script like this. And then other objects could access the DataManager via FindObjectOfType(). However this doesn't feel like the best solution so I was wondering if there was a better alternative?
(Its especially annoying, that I cant use FindObjectOfType<DataManager> in a Start function and instead always need to have some short delay before trying to acess the DataManager)
Use Singleton or ServiceRegistry pattern. (Basically what you have, but instead of using the FindObjectOfType, access it though its Instance parameter)
So for saving and loading I use a singleton that which gives an access point for other classes to load and pull from. Then the singleton will be the one that handles reading and writing
Alternatively, you could dependency injection as well.
Thanks! I will look into that
public static class DataManager
{
public static int GoldCollected;
public static int LevelsWon;
}```you could also do a very basic static class like this
anywhere you want to access it, its as simple as DataManager.GoldCollected
beauty is you never need to create an instance of the class beforehand, it always exists
thats really cool
its not really recommended to use static like this unless you're really sure its what you want. what you had above was already the singleton pattern so its confusing why you use FindObjectOfType in the first place.
I see. I'll look more into singletons then
were you blindly following a tutorial/using AI? the code you put above is a simple example of the pattern already...
charactercontroller + rigidbody will conflict as both will try to control transform. not sure if navmeshagent would also do that
I think I just looked up how to make objects persist between scenes and thought good enough lol
Thanks!
Is there an easy way to rename scripts (and their references) in a local package? When I use VS rename function the change doesn't "stick".
Only packages in Packages/ wont get auto re downloaded on change
I've been trying to position a gameobject on the left edge of my camera (a pixel perfect camera, I might add) through code, but the size of the "game" pannel in the editor changes the values of both Screen.width and Camera.main.pixelWidth.
Is is a bug? How should I obtain this data instead?
Use the pixel width/height of the camera as Screen reports incorrectly in editor
I've also noticed Screen report different values randomly in editor so I gave up using it
Camera.main.pixelWidth is incorrect
are you sure? Its correct for me and often Screen reports my monitor resolution instead.
Anyway you could just do viewport -> world pos
I don't see how that would help me. Isn't this only useful when you want to know where something is relative to the camera's center? I need to know where the edges are: my camera's location is always 0 0
i mean, i'd expect both of those values to change
viewport is 0,0 -> 1,1 so you can get a corner in world space easier
since you're changing the viewport, and the height of the camera (in world space) is what stays consistent
also, is it a plain gameobject that you're positioning in the world (2d or 3d?), or a canvas element?
oh, that's how it's mapped? great then
2D gameobject
then what rob said, yeah
alternatively, you could get the world-space halfwidth (camera.orthographicsize * camera.aspectratio) and offset your game object from the camera by that (perhaps minus half the width of the gameobject/its sprite if you want it to left-align)
Unity is fucking with my mind. My player is constantly triggering an "on trigger stay" from an object that's miles away...and disabled!
I went through everything, and it always triggers, all the time
I just can't understand why that would happen
is this just a hopeless bug?
you'd have to show us screenshots, code, etc.
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
private void OnTriggerStay(Collider other)
{
if (other.CompareTag("crawl") && !FlashlightRotation.flashlightOn)
{
Debug.Log(other.gameObject.name);
controller.radius = 0.05f;
controller.height = 0.2f;
controller.center = new Vector3(0, 0.63f, 0.57f);
if(!enteredWithFlashlight)
{
EnterCrawl();
}
}
}
this should be the relevant code
alright... and the rest? WHich script is this code part of? Which object is the script attached to? What other components are on the objects? Where are the objects located in the scene?
What is getting logged in the console?
as for the script, this is the line that is triggering, I would think the rest is irrelevant
the triggered object is logged
I mean I can show the screenshot of the empty object but it's miles away AND disabled
Yes that would be a good start
show screenshots of all the obejcts involvedc
including their inspectors
and a screenshot of the console logs being printed
I wasn't asking for the rest of the code. I just want to know which script this is and which objects i'ts attached to, which are very relevant information
I mean ok
this is my player with the new test terrain
selected is the object which triggers the on trigger stay
you can't see it, but it's very far away
and also disabled
looks like it's right here, no?
the player is the one with the script, triggering thestay
no it's not
different angle:
it's like hundreds of meters away
but that shouldn't be a factor, as the object is disabled
and hwo do we know it's this object anyway
I'd also like to see any and all colliders on the player
It would be better to see the screenshots during playmode too, while the logs are printing
what do you mean? Debug.Log says so and it's the only one with that exact name.
so I fixed it by disabling the collider on that object, on top of disabling the object itself
that has got to be a bug
I'm asking you to show me the logs
in so many words
Basically I'm just going through the motions of debugging
don't take it personally
This is what it was before I disabled the colliders
sorry no, that's a new log, now functional
OK so, when I disable the object, it always triggers it, regardless of proximity
when I enable it, it works properly
only god knows how that happens
if you can reproduce it, submit as a bug
aand now it's also triggering it when not touching when it's on
I don't know man
this is now interaction with a new, closer trigger
And here's the player collider
don't see any colliders here
See, now it's even further away
look on the head
Are you completely sure that's the only collider in the player's hierarchy?
I made sure to make the plaayer parent on 1 layer, and then let the collider only collide with that layer
your colldier setup on the zone doesn't exclude anything
The "include layers" thing you have there will include those layers in addition to whatever is in the collision matrix in the physics settings
yeah, cause only includes "player model"
aha
It additionally includes player model
so it should exclude everything but the player model
I will try but not feeling positive
I have a UI manager that manages what menu is currently open and all that stuff but I have some issues since I added these UnityEvents into the menu class, the events randomly stop working and then when I restart unity or enter play mode enough times they just fix themselves. How can I make events for each menu without getting all these bugs from serialisation issues ?
Wdym by them randomly stop working?
nope, doesn't work...one thing, it only happens when I turn off the flashlight and it always happens when I turn it off, because only then is it qualified to collide
but there is nothing in that flashlight script that references anything of the sort
Well one moment im in playmode and everything works perfectly fine, I spam all the buttons I try to break the events and it works but then when I re enter playmode and i carefully do a single action that triggers one of the OnMenuOpen events and it just completley breaks telling me that the target of the UnityEvent went missing eventho its still there
Can you show the code and the exact error you're getting?
This is the menu class
[Serializable]
public class menu
{
public string name;
public List<GameObject> menuObject = new List<GameObject>();
public Camera camera;
public string parentMenu;
public InputActionReference shortcut;
public UnityEvent OnMenuOpen = new UnityEvent();
public UnityEvent OnMenuClose = new UnityEvent();
[HideInInspector] private bool currentState = false;
public void ChangeState(bool state)
{
// only do events when the state actually changed
if (state != currentState)
{
// invoke corresponding evens
if (state == false)
{
OnMenuClose.Invoke();
}
else if (OnMenuOpen != null)
{
OnMenuOpen.Invoke();
}
}
// change the state of all the menu objects
foreach (GameObject obj in menuObject)
{
obj.SetActive(state);
}
currentState = state;
}
}```
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
it looked correct in the message preview
alright and - again what's the exact full error message you're receiving?
go to the very top of your console
scroll down until you find the first error
click on it so you can see the expanded full error message underneat
copy and paste that expanded full message here.
ObjectDisposedException: SerializedProperty lastOpenMenu.OnMenuOpen.m_PersistentCalls.m_Calls.Array.data[0].m_Target has disappeared!
UnityEditor.SerializedProperty.get_objectReferenceInstanceIDValue () (at <da771086bc2e4cfc9ad0a72e083a7f98>:0)
UnityEditor.EditorGUIUtility.ObjectContent (UnityEngine.Object obj, System.Type type, UnityEditor.SerializedProperty property, UnityEditor.EditorGUI+ObjectFieldValidator validator) (at <da771086bc2e4cfc9ad0a72e083a7f98>:0)
UnityEditor.UIElements.ObjectField+ObjectFieldDisplay.Update () (at <da771086bc2e4cfc9ad0a72e083a7f98>:0)
UnityEditor.UIElements.ObjectField.UpdateDisplay () (at <da771086bc2e4cfc9ad0a72e083a7f98>:0)
UnityEngine.UIElements.VisualElement+SimpleScheduledItem.PerformTimerUpdate (UnityEngine.UIElements.TimerState state) (at <e66f217a64a747d48b478f0d70978704>:0)
UnityEngine.UIElements.TimerEventScheduler.UpdateScheduledEvents () (at <e66f217a64a747d48b478f0d70978704>:0)
UnityEngine.UIElements.UIElementsUtility.UnityEngine.UIElements.IUIElementsUtility.UpdateSchedulers () (at <e66f217a64a747d48b478f0d70978704>:0)
UnityEngine.UIElements.UIEventRegistration.UpdateSchedulers () (at <e66f217a64a747d48b478f0d70978704>:0)
UnityEditor.RetainedMode.UpdateSchedulers () (at <8ad9ecbe25e14b10b6dde783af6e4aa2>:0)
InvalidOperationException: The operation is not possible when moved past all properties (Next returned false)
UnityEditor.SerializedProperty.get_objectReferenceInstanceIDValue () (at <da771086bc2e4cfc9ad0a72e083a7f98>:0)
UnityEditor.EditorGUIUtility.ObjectContent (UnityEngine.Object obj, System.Type type, UnityEditor.SerializedProperty property, UnityEditor.EditorGUI+ObjectFieldValidator validator) (at <da771086bc2e4cfc9ad0a72e083a7f98>:0)
UnityEditor.UIElements.ObjectField+ObjectFieldDisplay.Update () (at <da771086bc2e4cfc9ad0a72e083a7f98>:0)
UnityEditor.UIElements.ObjectField.UpdateDisplay () (at <da771086bc2e4cfc9ad0a72e083a7f98>:0)
UnityEngine.UIElements.VisualElement+SimpleScheduledItem.PerformTimerUpdate (UnityEngine.UIElements.TimerState state) (at <e66f217a64a747d48b478f0d70978704>:0)
UnityEngine.UIElements.TimerEventScheduler.UpdateScheduledEvents () (at <e66f217a64a747d48b478f0d70978704>:0)
UnityEngine.UIElements.UIElementsUtility.UnityEngine.UIElements.IUIElementsUtility.UpdateSchedulers () (at <e66f217a64a747d48b478f0d70978704>:0)
UnityEngine.UIElements.UIEventRegistration.UpdateSchedulers () (at <e66f217a64a747d48b478f0d70978704>:0)
UnityEditor.RetainedMode.UpdateSchedulers () (at <8ad9ecbe25e14b10b6dde783af6e4aa2>:0)
this is also an editor bug
NullReferenceException: Object reference not set to an instance of an object
InventoryManager.OpenMainInventory () (at Assets/Code/Inventory/InventoryManager.cs:115)
UnityEngine.Events.InvokableCall.Invoke () (at <17484a9af6b944dea5cd9be4dbb0da2c>:0)
UnityEngine.Events.UnityEvent.Invoke () (at <17484a9af6b944dea5cd9be4dbb0da2c>:0)
menu.ChangeState (System.Boolean state) (at Assets/Code/UI/UIManager.cs:162)
UIManager.OpenMenu (System.String name) (at Assets/Code/UI/UIManager.cs:62)
UIManager.Update () (at Assets/Code/UI/UIManager.cs:38)
Ok so it's happening in InventoryManager.cs line 115
thats this line
but I only get this specific error when all the other errors happen aswell
SO looks like either primaryOpenInventory is null or UIManager.instance is null or UIManager.instance.lastOpenMenu is null
I would add some Debug.Log right above that to find out which one is null
or attach a debugger there
based on this trace it looks like the unity event part is working fine
it's just an error inside the listener itself
Im pretty sure its the UIManager.instance.lastOpenMenu
like this ?
yes but it's possible that third one will throw an NRE itself. In which case - we'll at least know what the problem is.
I have a different problem, it fixed itself again and I cant reproduce the error anymore
probably some kind of timing or race condition issue then
Although
Was it happening only when the inspector was open before?
Maybe reopen the inspector if you closed it?
I dont think so, I can spam the inventory open and close and spam all other menu opening shortcuts inbetween and it works but when the bug is present it wont even open the menu if all i do is press a single button
I reproduced it, its the lastOpenMenu
what should I do now, if the last open Inventory is null idont want to trigger the return function
What should happen if it's null?
I want the open inventory function to continue as usual
var lastOpenMenu = UIManager.instance.lastOpenMenu;
if (!primaryOpenInventory.solo || (lastOpenMenu != null && lastOpenMenu.camera != null)) {
return;
}```
something like this
TRU thanks, forgot about that
deleting so its not a double post
Quick simple question, is there an attribute to grey out properties as shown above, the example was done with a custom property drawer, I just want to do it for a value that is only there for display purposes, greying it to clearly show that
simply out, if it exists what would GreyOutAttribute be in this example usage [SerializeField, GreyOutAttribute] private float currentSpeed;
ah ok
You would need to write a custom editor script
thought read only doesn't serialize
that's what I meant to linik^
thought so, won't bother for now then
NuaghtyAttributes REadonly doesn't affect serialization
Naughty attributes is free if you want to look into at some point but yea 😦 there isn't anything built-in
fair enough, was only for display purposes, thanks for the quick response
Hi
I want to dragf & drop MonoBehaviour (components) from my inspector to a var
How I can do this?
Thx
You make a public or serialized field of the script type, then that field will show up in the inespector. and you can drag things into them.
I don't have Transform or GameObject, MonoBehaviour with interface like this -> MonoBehaviour, IBossAttackPattern
I can't drag & drop my component into this public List<Component> patternScript = new List<Component>(); or replace with MonoBehaviour
this works for any type that is serializable, show exactly what you're trying to do
are you dragging instances of those MB ?
or are you dragging the textfile / textasset
are there some type of custom constraints on those fields ?
What do u mean?
I have this :
public List<MonoBehaviour> patternScript = new List<MonoBehaviour>();
And BossManager:
public List<BossPhase> Phases = new List<BossPhase>();
inside BossPhase
public List<MonoBehaviour> patternScript = new List<MonoBehaviour>();
so there are no custom attributes or anything ?
It might be because its a SO?
ahh
I gotta recall how it handles scene components, I think that might be the issue
It was the problem
yeah that makes sense now
what threw me off a bit is the inspector showed what was inside the SO in the list? i dont recall doing it by default no?
is there a custom inspector / property drawer there or am I just misremembering?
I use NaughtyAttributes which add a lot of attributes like showing the SO in inspector
ahh ok makes sense, normally it would in a struct / class
in Unity 6 getcomponents gets the components of a certain type in the order they are in the inspector or is their order not reliable?
pretty sure order is not guaranteed
if you need a specific order for some reason you should instead use a serialized field for the array and assign them manually
Can you explain more? It sounds interesting
iirc, order is consistent but not any specific order (ie not guaranteed to be the order in the inspector)
@somber nacelle But how can I assign them in an array in the order they are in the inspector with/without getcomponents if getcomponents are not reliable?
arrays are ordered, you would just put them in the array in the order that you want them
damnit discord won't copy the message link
Ok but how can I get the components in a reliable order they are in the inspector
because getcomponents are not reliable right
surely you know how to read, yes?
use the array
we aren't telling you to use getcomponents
But how can I get the components?
assign 👏 them 👏 in 👏 the 👏 inspector 👏
Oh sorry I got it haha. But I forget to mention to get the components in a dynamic way, not manually
what is the actual purpose of doing this
because at this point, this is turning into an XY Problem
Because all the components are of the same type and on the same object
that does not answer the question i asked
what are you trying to make
So there's no way I can drag them into the public array because they are in the same object.
yes there is, just lock the inspector or open the properties for the component with the array and drag the components in individually instead of the entire gameobject. but you've still not bothered actually answering what the actual purpose of doing this is
I'm doing each system in separate scripts, and I want to run each function in a specific order if necessary, for example the player controller.
It's a noob question
But you answered me here, I didn't think about the hypothesis of moving the object component in the array, I believed it was the object itself lol
this does not answer why you have multiple of the same component on a single object nor why they must be in a specific order
hey, so I've heard using public variables is bad and using get and set like this is better. How do I get them to apear in the inspector now? [SerializeField] doesn't seem to work.
for auto properties you can target the compiler generated backing field for attributes using the field: attribute target like [field: SerializeField]
public setters are usually frowned upon if it's not meant to be changed from outside of the class, but public getters are usually fine for any case
thanks!
regardless, you're doing a public set get there so nothing really changes
public float Horizontal { get; private set; }
Is the idea you're probably looking for
[field: SerializeField] public float Horizontal { get; private set; }```
I actually do want to change the varibles from another script here
In that case just making a public variable is fine without the auto property
although technically the property is better in case you decide you want to change anything about getting/setting the value later on (such as adding validation code)
I see, yeah that makes sense
Anyone happen to know why my fill (on a horizontally filled image) is not working properly with this function?
private void UpdateCountLabel(int newValue) {
ammoCountLabel.text = $"{newValue} / {maxMagCount.Value}";
fill.fillAmount = currentMagCount.Value / maxMagCount.Value;
}
when currentMagCount.Value is 10, maxMagCount.Value is 12, it should be setting it to like 0.83, but instead its being set to 0, no matter what. Setting the label works, so the function it self is called when its needed to be called... so I'm quite confused
int divided by int results in an int
int/int strikes again
but its a float..
which value is the float
because newValue is an int and it sounds like maxMagCount.Value is also an int
just because the variable that holds the result is a float does not mean that the actual result of the math is a float. 10 / 12 is 0 because they are both integers. but 10 / 12f or 10f / 12 is 0.83f
ok so that is indeed the case, I see
cast one of the values to float and it will work the way you want it to
i just set(float)maxMagCount.value and its working
Thanks a bunch, I was trying to figure this out for like 30 minutes.
in Visual studio you can hover and see the op it will use which can help in future
Ah I see, thanks!
Can anyone spot why my Angle method is returning the opposing sign I would expect? The values are correct, just not the sign.
private float GetAngle(Transform hotspotTransform)
{
Vector3 targetDir = hotspotTransform.position - firstPersonTR.transform.position;
targetDir.y = firstPersonTR.transform.position.y;
Debug.Log($"Angle for {hotspotTransform.name}: {targetDir}, {Vector3.SignedAngle(targetDir, firstPersonTR.transform.forward, Vector3.up)}");
return Vector3.SignedAngle(targetDir, firstPersonTR.transform.forward, Vector3.up);
}
The Object with the Video graphic is Hotspot 3, I should mention. The selected object is the firstPersonTR transform in the method
Try commuting the arguments of SignedAngle? it's probably just backwards
Also! How do i make one screen space overlay canvas render on top of another screen space overlay canvas?
(they're from different scenes)
there is an order value you can change
looks like you have a duplicate of this script
anyone here familiarized with fish-net networking?
thx
Could someone help me with this code, i wanted to add a knockback effect when the enemy hits the player but it didnt seem to work. i tried to simulate it and found out that the moveInput was resetting the x velocity.. there must be a simple way to solve this right
private void Update()
{
if (Input.GetKeyDown(KeyCode.K))
{
rb.AddForce(new Vector2(-100, 100), ForceMode2D.Impulse);
}
Attack();
movInput = Input.GetAxis("Horizontal");
Jump();
rb.velocity = new Vector2(movInput * moveSpeed, rb.velocity.y);
clampedX = Mathf.Clamp(rb.velocity.x, -maxAllowedVelocity, maxAllowedVelocity);
clampedY = Mathf.Clamp(rb.velocity.y, -maxFallSpeed, maxRiseSpeed);
rb.velocity = new Vector2(clampedX, clampedY);
}
}
add a new knockback vector:
Vector2 knockBack;
void AddKnockBack(Vector2 knockBack)
{ this.knockBack += knockBack; }
void Update() // everything physics-based should be in FixedUpdate()
{
rb.velocity = new Vector2(movInput * moveSpeed, rb.velocity.y) + knockBack;
//Reduce knockBack over time (this is a bad way)
knockBack -= knockBack * 0.02f;
}```
disable your normal movement code during the knockback
Hi everyone,
I have an issue regarding the TMP plugin :
I am making a WebGL game and the issue I'm facing is the TMP text appears to be fine when I am playing inside unity play editor but as soon as I upload it on a site (itch.io) the text shows up initially but when I switch to full screen the text seems to be disappearing from the game and when I load the game on full screen the text appears but when I exit the full screen mode the text vanishes
Is there something I'm missing here or is this an issue with the tpm or is this the issue from the website side? For now I have used legacy text which is working fine but because of legacy I can't use the option given in tpm and I can't design the text on my own from unity
so i made a helper function in another script to return a random bool by weight but it keeps returning false,if i do it without the weight parameter it works with no problems,does unity have problems with handling methods with parameters? (i also tried the unity random instead of the system one but it also gives the same result)
public static bool RandBool(int Weight) { System.Random r = new System.Random(); int result = r.Next(0,Weight); if(result == Weight) { return true; } else return false; }
Hmm, r is a new random number generator.. I'm pretty sure you're only supposed to create a single generator
yeah i used that just for testing but i tried with the unity random generator and it still wont work
If Weight is 0.8, what should r.Next(0,Weight) give you?
its a int random generator not float
Oh sure, if Weight is 10, what should r.Next(0,Weight) give you?
If you can properly answer this question, the reason why your code doesn't work should be very obvious.
Place some logs and see why the result isn't the same as the acquired value - reminder that you should not be creating a new generator
It has nothing to do with that, their current code can only ever return false no matter what Weight is passed in.
r.Next(0,10) which should still work since ive used the same way over on godot
You haven't answered the question.
Something to consider would be
Meaning the value can never be the same as weight
yeah that too but the unity one is inclusive and that one doesent work either
It's exclusive as well.
Only float would be inclusive as the Random Range pattern often is used for selecting indices within some count/length of a collection - not ever wanting the count/length
it is? wait let me check
That's why I asked that question, if they have actually read the docs and tried to answer it, they will realize it can never return true.
it is...i thought it was inclusive too man working and programming messed me up damn
int to int random ranges are usually inclusive exclusive so its easy to use with arrays/indexed collections
is it a problem to make a script only for it to have 1 or 2 lines of code or should I merge lots of little scripts like this and differentiate what on the script they can do based on like their name/tag/layer/etc?
Depends on what they are doing
You shouldn’t be differentiating like that using names/tags/layers though
Maybe tags to filter the start of certain things but
sure, i'd probably use like a var of sorts to classify the object or something
i guess my issue here is that i have a button i want to make, and it only does one thing, and i dunno i feel like i could put this inside another script and have it be called if button exists or something similar, you know?
its better to make things to work with specific types as name/tag comparisons will be slower if used a lot
it wouldnt be any old script, there's a handful of scripts here that are all related
Depends on what the button is doing
its just destroying game objects and updating int values
buttons shouldn't be in charge of that imo, depends on how far we're caring though
its searching for specific children in a gameobject and destroying them if you need more info
well its supposed to be a reset button, so i dont know how else id do it ;/
one way or the other they gameobjects have to go away
Button -> UI script -> object -> RemoveChildren()
ideally almost nothing should be searching for specific things like that in almost any context btw
I mean more-so logically. if you imagine a big button wired up to some classic western TNT, it's the TNT that explodes, not the button
in this case I mention it because while the button might only have one job, here it should probably be telling something else to do something
so it should tell the parent object to blow up the kids?
depends on how naughty they are being 😛
🤔
code wise it's a good habit to try and avoid acknowleding the parent/child relationship of objects unless it's directly related (eg. how transforms are different depending on their parents/children)
you should be referencing objects and/or classes explicitly via exposed references in your script
is it still slow if i find by name inside a gameobject?
slow and bad
yup
i dont know why but i remember having too many publics being bad
ideally public should be used only when neccasary but its more for better code practice than actual game-changing. in this case you could avoid it by doing [SerializeField] before your field which lets you keep it as private/protected etc. but still exposes it in the inspector
Mmm i almost got it, im having an issue trying to check if a gameobjects children have children too
{
if(gridblock.transform.childCount > 0)
{
Destroy(gridblock.transform.GetComponentInChildren<GameObject>());
}
}```
Looks like a bad idea unless you've got very few objects in the scene
- Why do you even need to do that?
- GameObject is not a component
If you want all child objects, you can iterate over transform, which can be used as a collection directly
Although I prefer transform.children for clarity.
alright i got it to work, but does this look good or can i simplify it?
{
if (obj.transform.childCount > 0)
{
Destroy(obj.transform.GetComponentInChildren<DragThisItem>().transform.gameObject);
}
}```
grids is a list of 9 gameobjects im setting on awake
Can't you make a list of DragThisItem instead?
GetComponentInChildren can return null.
no you see im checking the list of game objects to see if they have children, and the children will always have DragthisItem
that's why i put if childcount > 0
That's an assumption.
wdym?
itd be a lot better defined if you had a class on obj that did this logic directly, and it could just store a list of DragThisItem. Then instead of having a list/array of GameObject it'd be your own class
If the objects have a child without DragThisItem, it will fail.
oh thats fine, they can only have a child if the child has DragThisItem, that's being done somewhere else ;P
Yeah but will this be the same two weeks from now?
When you don't remember coding this quirk
you know what they do have a class, you saying i should do this in there and then just call the function from where this is now?
Yes, that would be cleaner. This current approach feels icky to me.
yes thats exactly what my message was saying
i mean i dont feel like this will change, its a rudimentary crafting menu with only 4 different types of objects to craft with, but i guess if i felt like expanding later. plus im always bad at optimizing, is half the reason i come here 😭
I'm more concerned with code quality than optimization here. GetComponent isn't slow enough to care about most of the time.
Getchild(0) should be fine if the object can only ever have one child right? i cant seem to find some sort of destroy all children without running a loop which i feel is pointless cuz you know, 1 child...
It's defensive coding. You're protecting against future changes, and my instincts say that they're likely.
well its a crafting table, like minecraft, youre not really supposed to have more than one item in the slot
the code shouldn't break if that assumption breaks like that
Yes but they may have other children in the future if you ever add functionality
i guess what im trying to say is would a loop slow it down more than just something like GetChild?
not in any way that would ever remotely matter
oh ok
Seeing this doesn't trigger any performance alarm bells for me
This is something that gets executed once at a time, right? You can get away with a lot of looping in such a context.
the logic is just really poorly defined when you store stuff by GameObject and are destroying children like this. I would always try to at least have a class on the parent object storing what the children are
yep, all seems to work now. thanks guys 😊
i get what you mean, its just that the children are being instantiated. They kind of have to be ;/
What instantiates them?
It seems to me that class should also be responsible for destroying them, and generally keeping track of them.
a parent gameobject instantiates them when it no longer has a child (the child is dragged and dropped unto one of the grids, which parents it to that grid)
they dont have to be done in this way ever. instantiate returns a reference to what was created, you can pass that to the parent or just directly spawn it from the parent
that is what im doing
the parent spawns one when it no longer has a child, as i dragged the child somewhere else and parented it to it.
Then im destroying all these children that ive parented to the grid as a reset button
If the parent is responsible for creating it, it should keep track of it and destroy it.
but im deparenting it, and the new parent is dealing with destroying it, that's what we were all talking about before no?
Has anyone completed the create with code thing
not sure what that is, but if you have a question, don't ask to !ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
im not entirely sure what your setup is but regardless, something has to be moving the child object to this new parent. You could also directly call a method on that new parent telling it what was added
oh yeah it's doing that nw
https://learn.unity.com/course/create-with-code I think they mean this
In this official course from Unity, you will learn to Create with Code as you program your own exciting projects from scratch in C#. As you iterate with prototypes, tackle programming challenges, complete quizzes, and develop your own personal project, you will transform from an absolute beginner to a capable Unity developer. By the end of the c...
Looks fairly straightforward
A Vr game but I had to quit it bc the android thing didn’t download
I'm guessing that was your first "real" project? Surely your first ever project you attempted wasn't a VR game... right?
…
Is that bad?
When did you start this project?
A few months ago
No AI?
Completely dived in no experience
Degree?
Modellers degree?
College Degree
What u calling me smart or sum?
This is a question for #1157336089242112090 not help channel.
VR for me is actually easier than pc, but it's personal experience that changes that
This is a help channel?
Wait fogsight I do need help on smth tho
This isn't news though
Yeah
This isn't idle chat channel
It is for help Fogsight
Fogsight I need help on smth
I'm a beginner of course I would want to know ppl's first projects
@dry mica Don't ping people not in conversation with you. If have a question then !ask it.
: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
I see, thanks
!ask what do I do when the android build support doesn’t download
: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
No work
I have an issue in my game right now to where i have a script that allows the enemy to wander and follow the player if close which works but my issue is my enemy character falls flat on its face once the game starts and just drags on the ground. I don’t know if its something with the navmesh or what but Ive been struggling for a minute. If someone can help me please let me know
Look through #1180170818983051344 , ask people there or use a discussion channel like I pointed out.
Freeze ur Z rotation
unless it's a 3D game
Fogsight plz help me in #📱┃mobile
Read the bot message
Ask the question, don't ask an individual user to help, head there, ask, wait
It is a 3d game
Can't help yah... Strictly 2D for now
This would most likely be you aren't freezing rotation on your enemy rigidbody
Under constraints
This isn't code related. If you have a physics enabled character and you want to constrain its rotation to just stand you need to set it on Rigidbody.
Trying it now
@solid iron Don't spam the channel if you don't have an answer. Read #📖┃code-of-conduct
I can assure you offering help to someone, failing and then affirming that I can't help further isn't spamming. However, I'll take your recommendation into consideration.
Wouldn’t call it spamming. He/she did give me a similar answer 😂
i mean, same thing, just freezing both x and z instead
I think i figured it out. Its due to the avatar configuration. Basically when i imported it the avatar started with its x axis rotated 90 degrees and i was setting it back to zero. Especially 0 is it flat on its face and 90 was it standing up
So even when freezing x and y it would still go to zero😂
i have an object with a bounding box and have a function that checks if the bottom of the object is touching the ground via a boxcast
public bool IsGrounded()
{
//Build an rectangle cast based on the width of the object's bounding box and extends 0.1 units below it. Returns true if touching terrain collision layer.
return Physics2D.BoxCast(new Vector2(coll.bounds.center.x, coll.bounds.center.y - coll.bounds.extents.y), new Vector2(coll.bounds.size.x, coll.bounds.size.y-(1.5f*coll.bounds.extents.y)), coll.gameObject.transform.eulerAngles.z, Vector2.down, .1f, colliderBlocks);
}
The boxcast is represented by the thinner rectangle under the object. The issue is that when the object is turned, the boxcast remains at the 'true' bottom of the object, instead of rotating along with the transform. This means that if the object is rotated, the ground check is on the wrong side of the object, and if the object's scale isn't a 1:1 ratio, the size of the boxcast changes too.
is there some way to keep the proportions the same and position/rotate the boxcast to always be relatively below the object?
It looks like it maybe affected by the scaling dimensions. If you scale something you should make sure that it is a child object and not parenting something under it or using its dimensions for calculation (or include scaling into it).
Anchor point used for calculation on the unscaled parent object and use that as casting coordinate
When you rotate the box the bounds will automatically adjust to the rotation. It's a bounding box after all.
Further added the z rotation in your BoxCast is likely redundant and causing an issue.
oh you mean including the z rotation in the boxcast check
should it just be 0 degrees then?
yes
yeah you're right, it was redundant
there are child objects under this object but nothing that would be affecting the IsGrounded check, and the box collider itself is on the parent
Right, bounding box report correct dimentions on scaling.
i dont quite understand
when the transform rotates, and therefore the bounding box rotates, i want the boxcast check to rotate too. since the left and right sides of the box collider are shorter than the top and bottom, when the object is rotated, the boxcast shrinks to match the length of the new bottom of the object (what was previously the left side)
You'll need to detect which way bottom is facing.
i basically want the boxcast to do this
Bounds return box that doesn't care about rotation
i know transform has transform.bottom and stuff which also changes when the object rotates (i think)
so transform.bottom should always return the correct side of the object
yeah, thats what i assumed
how would i change the code to stick to whatever the transform.bottom is?
i guess i could save the bounds to their own variables at startup and use those instead
There's no transform bottom, you can infer current rotation from .z rotation value
90 = right, 180 = up, etc.
oh sorry i meant the opposite of transform.up
which is just the relative bottom of any object
yeah that'd be -transform.up
yee
you can use that as your direction vector instead of Vector2.down
Vector2.down in boxcast is the direction the boxcast moves to look for collisions
Note if rotation is slightly off, comparing to vector directions might fail.
it doesnt actually affect the position or rotation of the boxcast collider
I'm aware of that
Based on this picture you don't want the boxcast to always go down though
you want it go to down relative to the direction the object is rotated
which would be -transform.up
Is there a way to reference Components in the Editor? I'm guessing there is, since it's possible with Buttons (see screenshot), but I'm having no luck with discovering how.
I want to be able to reference any Component through a SerializedField and then disable it in script
public Behaviour myReference;
you could use Component but Behaviour is the subclass that has .enabled
The screenshot you shared is from a UnityEvent which actually allows any UnityEngine.Object, not just Components.
I tried Components and Behaviours, but as you said Components don't allow disabling. With Behaviours I'm having a hard time selecting the actual Behaviour I want to disable, however. I can only drag in/ select GameObjects and get a seemingly random Behaviour each time
Right click on the object you want to drag things into and select Properties (the last menu item)
this will open a special inspector window for that object
you can then directly drag components from the regular inspector window into it
That fixes it, thanks! I never knew that was a possibility
Note that Colliders and Renderers have .enabled but they don't derive from Behaviour, so if you want to include those you'd have to do something like:
public Component theComponent;
void DisableIt() {
if (theComponent is Behaviour b) b.enabled = false;
else if (theComponent is Renderer r) r.enabled = false;
else if (theComponent is Collider c) c.enabled = false;
else Debug.LogWarning($"Cannot disable {theComponent}");
}```
Thanks for the information. This'll do finely for now, and later on I think I'll write a custom drawer to make it less finnicky
Anyone got tips on optimizing my game? I’m using the urp
Step 1. Use the profiler and determine what your bottlenecks are
Step 2. Optimize those specific things that are bottlenecks
Step 3. go back to step 1
repeat until you are satisfied with performance
because they have different behavior regarding enabled?
nothing to do with different behavior. This is the only way to get the compiler to be happy.
i mean why colliders/renderers define their own enabled rather than deriving from Behaviour
Because Unity messed up 15 years ago when they designed the API and it's too late to go fix it now.
there's no satisfying answer here, huh 🥲
i'd have guessed it was because enabled affects more than Update being called for those components
Those components are implemented natively
they don't really use Update, not the way user scripts do
Measure. Always measure. Identify real problems and measure the results. If you go around guessing you're probably making things worse.
Whats the proper way to profile specifically SetData calls? or would it be better to convert my SetData to cmd.SetBufferData and profile that?
So, when trying to build my game I get this type of issue about type or namespace not existing
However in the editor everything is working. Most are from libraries, like this dev.nicklaj.butter is one of my libraries, while GgCore is a dependency for Folder System
Everything works in-editor but I can't get to deploy so could anyone explain what I'm doing wrong?
Looks as though it's trying to compile editor scripts for a build
I have A LOT of issues with dev.nicklaj.butter so I suppose I setup something in the wrong way in the assembly but I wouldn't know what. It's basically my own implementation of SOAP and everything is distributed as editor stuff https://github.com/xNicklaj/Butter
Is your asmdef set up properly?
I wouldn't really know how to fix that though
I would guess so? wait let me take a picture
The asmdef likely should be set to compile only in the editor
I haven't really understood what's supposed to go in editor and what's supposed to go in player in the package thingy
I have everything in editor
For example my Editor assembly is set up like this
it only will compile in the editor
Like in my case I suppose drawers are supposed to be editor only, while the rest is supposed to be for the build? Because it's things like scriptable variables, etc etc
Yeah looks like you're mixing up editor stuff and runtime stuff
you need to split them up
damn
You should have two assemblies. One for editor, one for runtime
the editor one can reference the runtime one, but not the other way around
but like scripts that go into game objects are supposed to go to runtime, right?
and also scriptable stuff
If they are intended for the build, yes.
Thanks, I'll try to fix this
you helped a lot
So now I setup everything in the following way
Green is in package/editor, red is in package/runtime
Each has its own asmdef of course, one is .editor and one is .runtime
What is happening now is that since I've separated the editor tools from the runtime stuff they can't see each other. How can I fix this? (first time making a package)
Notice also how both can't see each other, not only editor -> runtime
the stuff in your runtime assembly should not be accessing things in your editor assembly, your editor assembly can reference and use things in the runtime assembly though provided the asmdef has a reference to that assembly. but that dependency should only be one way because the editor stuff simply won't exist in a build so you won't be able to build at all if your runtime stuff uses editor stuff
I think I understand
So if I provide a way for others to create their custom drawers, I should also mention in the docs that their code should also be enclosed in a separate editor-only asmdef?
yes, or in a folder called Editor
Is there anything special about folders called Editor?
~~Yep, it's one of Unity's "special folders"
https://docs.unity3d.com/6000.0/Documentation/Manual/SpecialFolders.html~~
I'm a 🐢
Ah thanks!
Yeah my package is safe now
time to figure out all the other issues lol
So you know, "special folders" stop working inside asm defs
And remember you can use conditional compilation to have editor code in runtime asms:
#if UNITY_EDITOR
OH
Okay
This would have saved me some time to know ealier
thanks
You can put another asm def in a sub folder to make an "editor" folder be editor only again if needed
Thank you!
In the build, should I specify anything about my package name?
What I mean is, my editor can find my namespace
Dev.Nicklaj.Butter
and all its related functions. The scripts inside the package work, BUT when I try to build I get this:
So it's like my project scripts cannot access the namespace when building?
These issues are not there in editor ofc
I have it setup this way though
The only thing I could think of is that in my runtime asmdef I have turned off Editor, not sure if that's wrong?
well yea its gonna need to be used in editor if you want to actually do anything 🤔
But funnily enough in-editor it's working, when building for windows it isn't
is this code editor or debug only?
No it's runtime stuff
Pff I'm a moron
it's exclude platforms
not include platforms
HA
Why is it though?
the editor asmdef has include platforms not exclude
the runtime has exclude
I'm being played man
there is a checkbox to invert it
hopefully thats a joke cus little sleep over long periods is really dangerous
Quick question, how do you get the value out of a Tvalue, assuming you know exactly what type of value the result will be? Unity internal uses Tvalue, and im overriding a callback function to check the value of that callback, if it is 0 or 1, return, otherwise let it continue to work. (I know that i will only use it for 1 type of value, but unity itself doesnt know that)
protected override BindingResult UpdateUI<TValue>(in BindingContext context, ref TValue value) {
if((int)value <= 1) {
}
return base.UpdateUI(context, ref value);
}
its a generic type so cast it or use it as the declared base type
You can use pattern matching if (value is int i && i <= 1).
That doesn't usually happen but today I've been running on 3h for like 18 hours
that you so much, im so used to casting it like (type) value, and didnt know you could do vaue is type (typeVar),
ive used the is keyword for bool checking, but didnt know you could get it out
Actually why not just make your new function and call with the generic type already set? UpdateUI<int>(in context, ref value);
if you know its only to use with an int then why do funky business casting it
Its an override of a Unity function, so i didnt know if casting it would give a wrong signature
generic args are not some special unity thing and your overload should be valid
to be clear, overload and not a override if done differently
ahh, im doing an override, as im trying to stop some unity functionality in a callback, rather then creating a seperate method. turns out it doesnt work right with override, so funky type casting it is for now.
do remember to write back to value if you want to modify it as the cast will unbox it (i presume TValue is object)
Thank you, will keep in mind if i need to write back to it. How I'm doing it now is that if it satifies the condition, i do stuff with the context and return a sucess, rather then calling the base.
Does anyone know why building cannot find the unity default screen space ambient occlusion?
Is it possible to get the normal of a collider from a OnTriggerStay like you can with a raycast?
the parameter for OnTriggerStay is just the collider so you would need to separately query it for the normal with some sort of cast, although what would you expect the normal to be when one object entirely overlaps the other?
- Make sure all your quality settings are configured correctly.
- Make sure the relevant packages are up to date and supported by your editor version.
- Try deleting the library folder.
in my openworld game, I have divided the whole island in 64 chunk scenes so that only those chunk scenes are loaded which are near to the main character .
What I wanna do is batching the objects of those specific chunks loaded around the player in runtime
But the chunks will also unloaded when the player isnt near to those, but runtime static batching already makes up a huge combined mesh (which was created when the player was around those chunks of that island) , but now the combined mesh are still on the memory , thus when the player moves around different region of that island , the memory gets overloaded with those combined meshes created every time
I need to make those combined mesh's garbage created by runtime static batching instantly removed from the memory when the player is not around the chunk of those objects (combined mesh)
What should I do in that case? Please help dont ignore....(
You mention "runtime static batching". Does that mean that you're doing it manually in code?
yeah , using unity's static batching utility
Then you should check the documentation to see if it gives you any handle to the generated mesh that you can use to release it later. Or if it has any API to specifically release generates meshes.
If it doesn't, then your only option is to write your own batching implementation
it seems this is the answer (kinda)
he can destroy that from the memory addressing that specific combined mesh created by static batching utility
but in my case , the combined mesh created by runtime static batching , I dont know its name neither I have any word to address it so that I can destroy that combined mesh ...because it's "void" here , what could I do to address that combined mesh somehow?
Im stuck here , it seems Im close to the solution but no clue how to head towards further
Since you don't have any reference or handle of the mesh, you can't really destroy or release it manually.
And since the documentation doesn't mention anything about it's lifetime, you can only act based on assumptions.
Or you can change your implementation such that it doesn't rely on API that is so obscure.
If you chose to rely on assumptions, you could assume that it is collected by GC according to the same rules as any other asset. You also need to assume that it's only ever referenced by objects that you can destroy and not by some internal unity systems.
If these 2 assumptions are true you need:
- make sure that it's not references by objects in the scene. Another assumption is that it's referenced by the mesh filters that were used when combining it. If so then you'll need to make sure that they don't reference it and/or are destroyed.
- As most assets, it wouldn't unload automatically when there are no scene references. You need to either transition scenes, or call API to trigger collecting of unused assets. I think it was
Resources.UnloadUnusedAssets();.
I have a question about scriptables.
If I have this scriptable object, that PersistencyId is a string variable that is modified like this:
private void OnValidate()
{
if(string.IsNullOrEmpty(PersistencyId))
PersistencyId = Guid.NewGuid().ToString();
}
So my assumption is that whenever a new scriptable object of this type is created the UUID is assigned and then never touched again. When building, the resulting scriptable will have the PersistencyId that was assigned by the editor OnValidate. Is this assumption correct?
My head tells me it is, however my player gives me a null Persistency Id
So basically I want this value to never change across launch, because I will use it to find the correct identifier when saving and loading data
This setup won't de-duplicate if you copy an SO.
I also really hate OnValidate and don't recommend using it for almost anything.
Check that you're actually serialising the field, because it appearing greyed out in debug view would indicate to me that it's not
Why do I need the field to be serialized? I don't need to change it via the editor
fields being exposed in the editor are a byproduct of serializg them
thats not what serializefield actually does
serializefield ensures the value is actually saved (serialized) to the asset file
oof shit
that's probably what's going on
What does it mean when SerializeField is grey?
it's unnecessary/redundant
Attribute 'UnityEngine.SerializeField' is redundant on this declaration type. It is only used when applied to 'Field' declarations.
Ah so the thing is that I have this IPersistentData that defines PersistencyId and it's not accepting the serializefield due to that I believe
public fields are already serialized
I believe it's not being considered a field since it's inhereted from an interface
oh wait that's a property, mb
serializefield doesn't work on properties the same way, you need a different form
that's not why, no. it's not being considered a field because it's not a field
Can I inherit a field from an interface?
interfaces can't specify fields
You can use [field: SerializeField] on the property to have it serialize the backing field.
Or write the field normally, and do an old school implementation of the property.
It probably shouldn't have a public setter too
Huh with
[field: SerializeField, HideInInspector] public string PersistencyId { get; set; }
it disappeared entirely from the inspector in debug mode. Does HideInInspector also hide it in debug mode? I thought debug mode would show everything
Annoyingly it does affect debug mode
Anyways it works now, thanks everybody, I learned a lot
Using [field: SerializeField] is very useful.
Hi all 👋🏻
I'm writting to seek help in troubleshooting why "isOpen" bool variable value gets overridden from the initial "False" at Awake method to "True" when the OpenSideBar Method is called.
I've attached the script to the MainSidebarMenu prefab with StartOpen value set to False. MainSidebarMenu prefab is active in the scene. A button: "MenuButton" has OnClick event with MainSidebarMenu linked and OpenSideBar method chosen.
I've already reset the button and attached the method 4 times and I very confused why my isOpen value is True when I first click on the MenuButton. Second image depicts the logs, which clearly show that isOpen value is set to False on Awake and then due to some reason becomes True when I click on Button with OpenSideBar method attached.
Thanks everyone who can help in advance!
It must be changed elsewhere. R click and find all references to isOpen to check.
If still unsure, use a debugger to investigate further.
Make sure your VS is set up correctly too as it appears to not be (is the project generated solution open?)
I didn't get what you mean by: "is the project generated solution open". I opened the VS code by clicking on script from Unity directly, not opening it manually myelf
Lack of colour on these made me think its not.
Does the bar below the file tab say "Miscellaneous files" ?
anyway its a common issue for new people here: !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
yes, it says: "Miscellaneous files"! Thanks for IDE config message, will do it!
@steady bobcat I've fixed the issue. I've used Perplexity to find similar issues and it turned out to be quite a common problem in Unity. I added: "static" keyword to the private bool variable and now nothing changes!
Thanks for help
You should read up on some c# basics if you needed static all along
I definitely need as I am writing code and learning Unity solely based on what I really need to implement without watching any tutorials lol. Don't want to waste time on watching unnecessary tutorials, but reading fundamentals is needed.
Yea I get that. Knowing more about C# will help you a lot (and having your IDE work properly now too)
hi, i wanna make a player and enemy scripts which will have stuff like health, attack, and all that.
i have a basic outline but i'm not sure how to make it work.
the line csharp public class Enemy : MonoBehaviour at the top there, it takes from monobehaviour. i am unable to also make it take from AIBehaviour. unity then gives me some warning when I don't use monobehaviour. (image below)
will this affect anything or is that just because I've used private/protected variables in AIBehaviour?
edit: By the first line, I meant so I can override virtual voids if need be. I.E. The attack wont be the same of every enemy, but will still use some stuff from the base function
hope it all makes sense
AIBehaviour defines enemyObj.
Enemy also defines enemyObj, shadowing the one inherited from AIBehaviour.
it's not an issue in itself, but it's likely to be a mistake, hence the warning.
in this case it's most likely your own mistake of redefining the field that should be inherited
should AIBehaviour have an enemyObj in general?
for the attack thingy
probably not actually now that i think about it
then yes, you would remove it from AIBehaviour and define it only where it's actually used
alright, thanks!
(in the alternate route; if every AIBehaviour should have an enemyObj, you would remove the definition from Enemy instead, and let Enemy inherit that member from AIBehaviour.)
ahh. every aibehaviour will have attack but not enemyobj. thank you!
What's the best/most 'clean' way to manage collectible objects that each have a score value? I'm making a 'catch falling objects' game, with food that's worth points and hazards that cost points.
Would it be considered better practice to have their score value in each object/prefab and pass it along to the score manager in an event, or should the score manager have like the master list of scores and decide based on the object (via a 'type' enum).
have each object specify its own score
think about what you'd do to make a new one
in this approach, you'd just make the prefab, set the component, set the score
if you used a centralized store, you'd make the prefab, set a component to make it collectible, then go to the store and set a score there, maybe updating an enum definition and recompiling
I'd like having a list of scores in a ScriptableObject
And basically the same question about sounds too. Should everything carry its own sound(s) and talk to the Audio manager directly or should all sounds be invoked more centrally?
So I suppose this is actually a very general question I couldn't really find a good answer (esp since most tutorial videos neglect to mention software architecture in general). To what extent should the moving pieces (enemies, colletibles, etc) route their updates and such through some manager, or should they more directly talk to the relevant places? (Audio, score, maybe other enemies)
hm this is kinda more about where you keep data
well, the previous question would be about where you keep data
this is perhaps about where you keep links to assets
Separating data from functionality is generally pretty clean. Keep configuration stuff in ScriptableObject, reference that in your prefabs.
sparks up a question, if i'm using inheritance and stuff, do i use scriptable object for the class that will inherit from the big class or do i use that for the big class?
In C# you can only inherit from one class, so your base class should inherit ScriptableObject
ahh thank you
You can inherit from multiple interfaces. Depending on how much code you share between implementations that might be a better idea.
And sharing code can also happen through a third class which is not inherited
small brain fart. inheritance is Class1 : Class2 right?
Yes
yeah thanks
so if i made a monobehaviour script and just took away the monobehaviour part, all will be fine?
i wanna make my code not awful to read
then it wouldn't be a monobehaviour...?
if you're talking about the options in the menu you screenshotted above, for a standalone class, you'd probably start with "Empty C# Script"
How would a sciptable object for that look like? I know how to make one for like the settings of a whole level, but if I make an instance for each different collectible type, how is that different from setting the properties in the editor on each prefab? Or am I missing something?
you make say 5 instances of the SO and assign each to the respective prefab. The point is to separate this data from the prefab.
Also means its easier to share this data with multiple prefabs (or if swapped, share a prefab between multiple SO's)
So for my primitive example, the SO would have like the score value, falling speed and collision sounds, and each prefab only contains its SO instead of the actual values?
*references the scriptable object asset
Yeah, that's what I meant, my bad. Probably just via a SerializeField set in the editor?
