#💻┃code-beginner
1 messages · Page 388 of 1
You should probably look up how to make a list instead of guessing and waiting for us to tell you the guess is right
true
okay thanks guys
In C# the square brackets would be aligned with (next to) the type rather than the name.
@swift crag ?
The individual components can subscribe and unsubscribe
But you can also have the input manager decide whether or not to call methods, yes
The usual choices are (assuming every object being polled needs to be polled):
- individual polling: straight forward and easy to perceive what is happening/not-happening
- events: subscription based, where you're able to flexibly change whether or not objects should continue to be polled.
It's simply a design choice - you'd have to write (create) some sort of state base manager if you're wanting to later add removable polls as a feature.
It's a preference (other than doing more than simply polling)
i think ive run into a unity bug, i pressed the visibility icon on the object, but it doesnt get hidden, in fact no object gets hidden. Do you guys know how to fix this?
Unity’s scene visibility controls allow you to quickly hide and display GameObjects in the Scene view without changing their in-game visibility.
https://docs.unity3d.com/Manual/SceneVisibility.html
Would that be the scene view?
Maybe hit the toggle up top in the scene view
Im having issues with unity/unity hub, I was working on something until I got an error saying " Assertion failed on expression: 'res == EAGAIN II !HasAbortingErrors()’ ”, I deleted unity hub & unity editor, deleted the unity file out of my finder, reinstalled unity 2019.4.31f1, the iOs support & android package & I opened unity hub, added the package back to my projects tried opening it to reimport it all, everything is gone when I open it & I closed unity, went back to unity hub & tried to fix the manifest.json but it didnt work, it keeps telling me that theres an error with the indepence named accessibility that's stopping all my imports from importing & im still getting an error that says: "Assertion failed on expression: 'res == EAGAIN II !HasAbortingErrors()'" how do I fix both of these?
You'll need to share some screenshots of the errors and more context on what's happening.
this is my manifest.json code: {
"dependencies": {
"com.unity.ai.navigation": "2.0.0",
"com.unity.burst": "1.8.13",
"com.unity.collab-proxy": "2.3.1",
"com.unity.formats.fbx": "5.1.1",
"com.unity.ide.rider": "3.0.28",
"com.unity.ide.visualstudio": "2.0.22",
"com.unity.ide.vscode": "1.2.4",
"com.unity.mathematics": "1.3.1",
"com.unity.test-framework": "1.4.3",
"com.unity.timeline": "1.8.6",
"com.unity.ugui": "1.0.0",
"com.unity.modules.ai": "1.0.0",
"com.unity.modules.androidjni": "1.0.0",
"com.unity.modules.animation": "1.0.0",
"com.unity.modules.assetbundle": "1.0.0",
"com.unity.modules.audio": "1.0.0",
"com.unity.modules.cloth": "1.0.0",
"com.unity.modules.director": "1.0.0",
"com.unity.modules.imageconversion": "1.0.0",
"com.unity.modules.imgui": "1.0.0",
"com.unity.modules.jsonserialize": "1.0.0",
"com.unity.modules.particlesystem": "1.0.0",
"com.unity.modules.physics": "1.0.0",
"com.unity.modules.physics2d": "1.0.0",
"com.unity.modules.screencapture": "1.0.0",
"com.unity.modules.terrain": "1.0.0",
"com.unity.modules.terrainphysics": "1.0.0",
"com.unity.modules.tilemap": "1.0.0",
"com.unity.modules.ui": "1.0.0",
"com.unity.modules.uielements": "1.0.0",
"com.unity.modules.umbra": "1.0.0",
"com.unity.modules.unityanalytics": "1.0.0",
"com.unity.modules.unitywebrequest": "1.0.0",
"com.unity.modules.unitywebrequestassetbundle": "1.0.0",
"com.unity.modules.unitywebrequestaudio": "1.0.0",
"com.unity.modules.unitywebrequesttexture": "1.0.0",
"com.unity.modules.unitywebrequestwww": "1.0.0",
"com.unity.modules.vehicles": "1.0.0",
"com.unity.modules.video": "1.0.0",
"com.unity.modules.vr": "1.0.0",
"com.unity.modules.wind": "1.0.0",
"com.unity.modules.xr": "1.0.0"
}
}
You can share code-like text the same as !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Also, I'm not sure what that manifest is supposed to explain?
this is what happened after i tried clicking continue & reimporting everything
For starters, move your project out of the users folder.
Just an update you guys I got it working was very simple didn't have to use lists luckily https://gdl.space/lihizoxido.cs
Thats where my projects are normally saved though, won't that affect the folder?
You should normally avoid putting complex development projects in the user directory. Since different access rights can affect it.
Oh okay. I moved it to my documents folder, what do I do now?
Documents is still under the users directory
Move it to the disk root or somewhere nearby.
I moved it to the desktop instead since the only other options are applications & downloads
is it acceptable to project scale make void Reset a [Conditional("UnityEditor")]?
No. Desktop is under users folder as well... Can you not move it to the disk root as I suggested?
A disk root?
Im not sure where to find that..
If your desktop is at C:\Users\scarred\Desktop The disk root is just C:\
Because you can make folders, there are many many more options than that.
I need help where do I go from here
what are you trying to do
Use screenshots, not pictures of your screen, and describe the issue
open unity hub on your computer and make or open a project
Ok
Then where
What do you mean "then where"
That is the end.
You make or open the project, then... make the game
There is a lot to do after that of course, so it is hard to say anything specific
Use screenshots, not pictures of your screen
This
To be clear, none of this is to be done on any website
Stop
Ah yeah, thought they had it already. True true
Ok done
Follow the steps
after you install the hub, open it
insstall the latest editor version
then click to create a project
Here?
It won't let me move it there...
Unless I put it under system or another folder.
there's no way unity can run on a chromebook
didnt realize they're on a chromebook
I do not use mac, but can you put a folder there and use that?
I guess it WAS a good thing they posted that terrible photo haha
Nope, it still wont let me
is it just me, or there really isnt a docs for this attribute
it is undocumented
hope it works tho, this code of mine is dependent on it :3
everything dependent on OnENable, and dont wanna make a mini coroutine/delayedcall pattern to call them
it does work, all it does is set a default order for the script execution order for that type
anyone know how to make transform to poses
first video is my project
second video is an example of how i want it
animate it?
i mean rotate smoothly
slerp the rotation
i added animation when you click a button but it dosen't rotate smoothly it just like clips something like that
you don't need to animate the rotation, that doesn't actually make much sense. just keep track of the target rotation and slerp to it
i know i don't need to animate the rotation
then why did you?
slerp the rotation
look
the thing is that when i click a button but when you rotate a different direction it plays but it needs to rotate the pose as it needs to be as the animation
just watch the second video
what do you mean by that
i did. i still don't understand the issue you are experiencing because you refuse to actually describe what is happening in a way that makes any fucking sense
the second video
the animation rotation start is in front like Y90
but when you rotate the camera to like Y120
and when you press a button or something the camera forces to rotate to Y90
again, if this is all about rotating an object, you do not need to animate it. just slerp its rotation
and how do i slerp rotation
that's why im asking because i never did this and i need help
you start by googling "unity slerp rotation"
you are required to put effort into your issue or you won't get it fixed. i am not about to do the work for you
can we do this wothout custom editor?
or hopefully an attributed string that I can use to any other script
You were given direction. That is the kind of help you get here. If, after you put in effort and learn a bit, you can come back and show what you tried and we can guide you more from there.
Slerping is definitely the right choice for this. It was a good direction
this is not something that is built in, you'd have to use a custom editor or some asset that does it
Specifically the black outlined part?
just as long as there's a text that the user will laways see
probably clean as well (for presentation purposes)
Header attribute is the closest that comes to mind
hmmm.. that is quite a little acceptable maybe
actually, I can try to make an asset of it
with a prop drawer
aight imma do that Ig
should be pretty trivial to create something like that using a decorator drawer
property drawer is for drawing properties, decorator drawer is similar it draws information or other decorations. the Header attribute is an example of one
Im currently leaning to make it likecs public DisplayString xsd123 = "This is a tutorial covered by a box"; is that deco drawer better than prop drawer?
it's not "better", it accomplishes a similar, but different, function. and you wouldn't need extra data in your class, just an attribute attached to a field and the string can be passed to the attribute's ctor instead of being stored as part of the class
hmm, imma go with prop on this one ig, it will be more versatile for the purpose(as it can be placed on classes that dont have fields), can turn it into a conditional compilation to not hurt runtime if that's just the drawback
thanksuu
can be placed on classes that dont have fields
how though because you have to create a field for it
I was describing a propdrawer there
ah i get it
yea, but it doesnt directly require you to make something else 
then where is the display string coming from if not from "something else"
prop vs decor?
also why would you have inspector documentation for something that doesn't have anything in its inspector anyway? that's what normal documentation is for
basically a small text explaining what the thing can do :>
like notes thingy
ohhh can a class be decorated? Rather than fields?
if it can it would be like better
yes i understand what the point of the tutorial text you are trying to create is for. but why would it be on something that has nothing at all in its inspector?
if it has nothing in the inspector at all its documentation would preferably be with the rest of your actual documentation and not require someone to stumble across the component and add it to an object just to find out what it is
some of my components just needs to be attached and will do it's job automatically on certain callbacks
just extra ways to tell peeps what things can do cause my naming skills is bad 
right so your actual documentation that you ship with the asset should contain that info
is that enuff tho?
i mean theoretically yes. but it's your project, do what you want 🤷♂️
I wouldn't want to have to randomly add components to see what each component does.
quite insecure my inspector is ugly, figured imma add just extra stuff to .... make it look a little detailed
A lookup document would suffice and be preferable.
this already exists! they just need to use the HelpURL attribute
Nice
aight 
this is not an example of the type of component i was referring to. this has stuff that needs to be configured in the inspector so having some text explaining it there would be helpful to supplement the documentation (but not replace it)
i was referring to a component that has no fields since your complaint about the decorator drawer was specifically the need to add a field to that class for that purpose, which i pointed out was what you were required to do for the property drawer anyway
is there any way to make a script update faster or something? Basically i have little smoke sprites that appear as "trail" behind the missile. At slow speeds it works nicely but at high speeds it barely shows and theres massive gaps. Any ideas?
Update runs every frame already. that's about as fast as updating a component will go. it seems like there may be some issue with whatever logic you use to do that
you're moving too far in a single iteration
most likely
okay. I think i need to limit the linear velocity tbh. The missile controls feel fine until it gets going real fast. It doesnt feel like theres enough drag or resistance (i havent taken physics yet idk the term)
You would have to spawn more of them between the last and current frame's position, relative to the distance traveled
If you'd use the particle system then it would handle it for you, theres a 'Rate over distance' setting
Ok i'll have to see what i can do with it. Thank you
havent looked into the PS but the problem is you need some linear interpolation
vfx graph I do some of that as it'll leave gaps for those quicker projectiles
hi guys, i can't create a prefab variant of this prefab cause the option isnt in the menu.. i followed the docs... but i dunno why its not showing up
drag it on the scene, rename it then drag it back into assets
what does "static" in scripting mean?
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/static
makes stuff associated with the type rather than an instance
did unity provide a code for these presets? Manually writing them by code is grindy
What should I do now since I can't?..
There are many who manually wrote them, for example https://discussions.unity.com/t/solution-set-ui-recttransform-anchor-presets-from-code-c/170367
id call a foul on unity for this one
why not make an accessible codes/api for it when it is already written
it looks nice tho, thanks for these (and the author)
Like every piece of software Unity is no where near perfect. You can make a suggestion on the public roadmap.
This probably falls in the category of not worth supporting since people can bang it out in 20 mins for their own projects
Hey,
I'm trying to implement moving my character using the CharacterController. I have the same code from https://docs.unity3d.com/ScriptReference/CharacterController.Move.html) and it works.
But now I want my character to be always facing in one direction (to the front), but when I click 'a' or 'd' to move it to the left o right, it start facing those directions. I'm a bit stuck on how to achieve this while using ´controller.move´
please see #854851968446365696 for what to include when asking for help. you haven't actually specified what part of that you are struggling with nor have you provided relevant code
why when i add this line of code does it randomly start giving me the error: "'Random' is an ambiguous reference between 'UnityEngine.Random' and 'System.Random'"
also idk if im even doing that right i just looked it up
but when i remove that line of code my Random.range(x,x) works fine
because you did not specify which namespace you are accessing Random from. both UnityEngine and System have a Random class. you need to specify which Random class you are using . . .
‘’’if (move != Vector3.zero)
{
gameObject.transform.forward = move;
}’’’ this piece of code turns your character in the direction of movement
okay how do i specify?
oh my bad i see now
by using the fully qualified name. refere to what boxfriend mentioned: <#💻┃code-beginner message> . . .
So why does it give me the error only when i type that line of code? is it because I dont use one of the namespaces until i reference Convert or smth like that?
and then it starts using it?
so i must not use anything in the System namespace until now then?
did you not bother reading the link i sent?
i'm not sure why you're using Convert in the first place . . .
Ty
Because im a beginner and idk what im doing so i googled it and that was the top result
I dont see the answer to my question
ah wait, i think i misunderstood this message. you are very likely not using anything else that requires importing the System namespace
but like i said, the Convert class is in that namespace, although i don't really see the need for the Convert.ToInt32 call here, just cast
okay so when i use convert then it starts calling system and thats when it sees two versions of Random, yes?
im trying to understand how the code works as well as fix it
it's not "calling" System. you've added the using statement for the System namespace so now it sees those two Random types with conflicting names. this part is all spelled out in that link i sent
the using statement has been there since the start
when you use Convert, your IDE adds the using System; namespace to your script. this gives you the conflict with System.Random and UnityEngine.Random . . .
not the System one. that is not is not included in unity's MonoBehaviour class template
yes, when you autocompleted the type name for Convert
i see now, thank you
do you have a better suggestion for what im doing? im trying to round down to nearest whole number if its not clear
Mathf.FloorToInt
or just cast the result of the Math.Floor call to int using (int) which is literally what Mathf.FloorToInt does anyway
Do i need mac to export my game to macOS?
Yes
Idk, it's probably more about the utility more than time cost. You can add gravity in a few lines of code, but "UseGravity" was added as a toggle to rigidbody components since it's useful despite it being easy.
you'd only add the namespace to your script if you are accessing many methods from within that namespace. this is easier than using the fully qualified name, like UnityEngine.Rigidbody or UnityEngine.Transform every time you want to declare a variable . . .
oh okay so i can call the namespace without the Using script?
you can use an explicit cast to an int with (int) or use a method from the Mathf. library . . .
this message makes very little sense
You can reference modules by referencing the entire namespace. The using keyword is a convenience.
I would say adding gravity to a closed component such as the rigidbody is much more difficult
yea this is what I was asking
even for iOS export cuz i dont have an android?
That's a bold statement
Embrace change and improvements, yes?
I like this philosophy more.
Yes. You need XCode to build to mac and iOS you also need a pple dev account and pay $100 per year for it
You do know unity is changing, and updating like every 2 weeks
Sure, never said it wasn't
i believe you mean, you can access a class or function by using its fully qualified name (inlcuding the namespace). . . .
damn lol
"Just deal with it" is not quite helpful and not very empowering
I also find it dumb that this api is missing yes. Like a said it warrants a suggestion on the public roadmap
without typing "Using namespace" first is my question
but Travis answered
this is how you can start separating your code into modules for reusability and modularity . . .
yes, i figured that's what you meant . . .
i just want to point out that you should be able to build a mono application for macOS on windows. afaik it's just il2cpp that will require the mac to build.
also notarizing the build requires a mac but that is technically a separate step from building
if im understanding this right, is it possible to get a specific axis from a vector3 variable?
for instance. i have the variable 0.00, 0.00, 0.50 can I get only the z value from this variable? or the third, 0.50 value. im still trying to wrap my head around this, sorry if im asking stuff weirdly
check the docs
I dont think so. Last time I checked “building to mac” outputs a xcode project regardless of mono or il2cpp
Yes, a Vector3's three numbers are accessible as properties.
Vector3 myVector = new Vector3(0.00, 0.00, 0.50) can be accessed through myVector.x, myVector.y, and myVector.z for the three numbers.
myVector.z would return 0.50 in this case.
there's a toggleable option to create an xcode project
does anyone here runs linux to test my game?
if you want people to test your game then post in #1180170818983051344 with a link to a reputable host site (like itch.io)
ooh okay
Hey! i'm making a pretty simple character system and i just wanted some advice. So far I've made a simple character class, and a couple other classes that inheriet from it, and set some basic data. How can I make a list of these inherited classes to choose between? Or does anyone have any better ideas on how to create a better frame work for handling data like that.
At the moment i'm setting a bunch of basic stats, like health, move speed, ect, then i'm trying to assign the class to the player, read the information off the class, and use it accordingly
Sounds to me like a job for Scriptable Objects 🦸
My immediate hunch is that inheritance might be inferior to composition here. Unity's primary architecture is Entity-Component System. Most of my early choices to use inheritance have been rewritten to use scriptable objects or just scripts
If you put serialized fields in your scripts, you can set these values from the inspector. If you want to pre-set them, you can use prefabs, and if you want to store configuration in a script, then consider using scriptable objects
hmm.. Scriptable Objects seemed awesome for the more primative data, but i'd also like each class to have functions written into it that can be ran. For instance, if the player pressed f, it would pull the function from the child class and then run it. Can i do something like that with scriptable objects?
I'm coming over from lua so i have an odd way of thinking about C# lol
I would make the PlayerController script hook up the logic in its OnEnable function such that OnPlayerPressedF --> DoTheActionOnF
It's not the performing of the action i'm stuck on exactly, moreso how the function will be accessed to be ran
Composition is a fine way to do this. The script can access another component OtherController and run a function stored in another script
It is hard to give specifics without a clearer understanding of your intended architecture / outcomes
The main question that needs to be answered is: What outcome should this have? Phrase it in terms of a use case, like "A player should be able to", and it will be clearer for me
I'm trying to make a framework (for a lack of a better word) that has inputs for basic information such as health,speed,attack,ect and then more complex information like functions (onAttack, onSpecial, onDeath) and then i'd like to use this framework to make classes that fill in these blanks to be used. Once my classes are done, i'd like to make some sort of handler script to read the data off the class, then process it. So again, if the player pressed "F" it would read the function onSpecial() from the child class, and then perform it
That's just the idea in my brain though, i don't know how feasible it is
The logic is 100% feasible, but implementation methodology is critical
So I'll explain how my architecture works, and you can see if this makes sense to you:
PlayerStats --> Mostly a data container.
PlayerHealthController --> PlayerDeathHandler
PlayerInputController --> PlayerMovementController
\--> PlayerInputController
PlayerUIController (Handles input and routes it to UI actions)
(Input) <--> (Affect Change) <--> (Store Data)
InventoryView <--> InventoryController <--> InventoryModel
It is not perfect and may become more organized as time goes on, but there is a clear separation between components.
What do the arrows represent?
If you want HealthController to be able to invoke a Death mechanic, you can store it in another script, and when HealthController's Health goes below 0, it can call a method in PlayerDeathHandler, or emit an event that PlayerDeathHandler listens to
The arrows represent the flow of input and action, just like you wanted to direct the flow between player input (pressing F) and action (movement, UI interaction, etc.)
In terms of storing data, you should do this with scripts that are intended to store data. In my example, it is the InventoryModel which is entirely focused on storing data, while InventoryController is focused on changing data
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
If it helps to break down the logic further, here's what one of the child classes looks like
public class DefaultClass : PlayerClass
{
public DefaultClass()
{
className = "Default";
health = new HealthSystem(150);
speed = 5.0f;
jumpHeight = 2.0f;
}
public override void UseAbility()
{
Debug.Log("Playing default class");
}
}
(currently)
The fact that this doesn't inherit from Monobehaviour is probably a problem
I think it might be best to embrace the ECS architecture and turn this into a data class instead.
public class PlayerStats : Monobehaviour
{
public string name = "Default"
public int health = 150;
public float speed = 5.0f;
public float jumpHeight = 2.0f;
}
public class PlayerInputHandler : Monobehaviour
{
private PlayerControls playerControls;
private AbilityController abilityController;
private void Start()
{
abilityController = GetComponent<AbilityController>();
if (!abilityController)
{
Debug.LogError("No ability controller found.");
return;
}
}
private void OnEnable()
{
playerControls.Player.UseAbility.performed += UseAbility;
}
private void UseAbility()
{
Debug.Log("aaaa I'm using an ability");
// Or, alternatively
abilityController.UseAbility();
}
}
Does this make sense?
PlayerStats is the only thing confusing me, because i'm still thinking about how different classes would have different stats. Everything in PlayerInputHandler i understand very clearly
I actually have my stats separated by class, too. I clumped them together for example
I have my JumpHeight and Speed in my MovementController
I have my Health in my HealthController
I have Strength, Dexterity, Constitution, etc. in my StatsModel.
And they communicate with one another by reading each other's data
For ease of access and creation, I'm trying to have all of the classes stats, functions, you name it in simple place. In lua i had one massive keyed table, with other tables inside it, holding the type of data i was mentioning. Then i'd just go to that key in the array and pull the function when i needed to run it. So i could simpy type [Classname].function() to execute an ability
I don't know if that's possible with c#, or even something close, but that's what i'm trying to recreate
This is an anti-pattern called a GodObject
It's possible, but your class will grow to multiple hundreds of lines long and you're going to wish you separated them
if you want to put thousands of lines in one script file, then be my guest, but separating them is considered good for modularity.
I was getting pretty worried about the massive scale, which is why i'm now trying to split them into sub classes/children of a base class
I absolutely agree
I would advise against using subclasses by default
While you can use inheritance, I think it's the wrong tool most of the time in Unity
The architecture is ECS, Entity-Component System, where components are scripts, the glue that holds everything together. If you use inheritance, things can get complicated and tightly coupled very quickly.
There's a saying, "Prefer composition over inheritance"
A script is a component, so it's preferable to inheritance.
What you appear to be doing is accomplishing ECS but through extra steps via inheritance
Hmm, i am pretty new to coding as whole. I've done it for a very long time, but i never delved into the truly serious side of things. Do you have any resources to further teach what you're describing?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
This is solid for Unity in general
But if you want to touch on the theory-side of coding, it is quite complex, so I recommend starting off with tailored questions when you search for answers.
The Wikipedia article is decent: https://en.wikipedia.org/wiki/Entity_component_system
Entity component system (ECS) is a software architectural pattern mostly used in video game development for the representation of game world objects. An ECS comprises entities composed from components of data, with systems which operate on the components.
ECS follows the principle of composition over inheritance, meaning that every entity is def...
The #1 way to learn, however, is simply to build.
Start off small and build a movement system. Then build a health system. Then build an enemy that just flies at you. Make the enemy damage you. Etc. Keep adding on and building things, and the principles will make more sense once you have the experience to understand the meaning behind them
I know it's sub optimal, but i'm super motivated right now and running over the basics again kinda sucks the life out of coding, so i'm more so tacking the issues i face head on
And i have the movement and health system currently, i'm trying to set their variables
I think you are in a tunnel right now, and if you just take one step back and pick a different path, you will still be stuck in the tunnel. I highly highly highly recommend you just do things the "Unity way" and accomplish your objectives this way.
You are doing things the OOP way instead of the ECS way.
I don't think you'll make it far if you try to headstrong pure OOP into Unity
I did the same thing when I started and I regret it
It won't take longer than 20 minutes if you just follow a tutorial to get the basics up and running and take it from there.
If you like ECS, why don't you use #1062393052863414313, that uses ECS in Unity?
I never looked into it
Plus, my project is deeply in progress. I might consider pivoting if I finish my current one
I'll give it a run by
Do you mean different numbers for the stats, or like actual different stats where some things may have X while others dont?
Id really just go with 1 stats class, regardless of if the character is using every single stat. Scriptable objects is a really good way of plugging in different numbers, instead of the example class you showed above. It would just copy values from an SO, suddenly everyones different stats can be represented by an asset in your folder.
When I build game, suddenly some changes appear in these files:
URP-HighFidelity.asset
BurstAotSettings_StandaloneWindows.json
CommonBurstAotSettings.json
It occurs everytime I build a game. Should I commit these changes?
Hmm, personally I dislike suggesting ECS for the normal monobehavior way that Unity works with.
Either work OOP in normal Unity, or ECS in DOTS.
Monobehaviors is ECS, for the most part
I think you should not default to inheritance in Unity scripts.
I'll be honestly, this all sounds quite out of my league. I'm by no means new but I'm pretty lost as to what most of this means haha. ECS seems preferable, but i don't think i have the means of skill to delve into it just yet
i think you are just taking the name "ECS" and applying it to something for what you think it is. ECS is a completely different workflow and really you said you never looked into it...
I suppose technically it would be GameObject-Component
I didn't look into DOTS ECS but components for composition is the essence of default Unity
OOP is certainly not the default design pattern
i definitely do not suggest actual ECS. theres is a major difference between composition and ECS. To put it in simple terms, composition is like "attaching scripts to an object, if it has the script, it can do this functionality". Inheritance is more "I have 1 script, i derive classes to give it unique functionality". Both have their use cases of when it is preferrable
Retroactively consider my mentions of "ECS" to be "Composition over inheritance"
Google is telling me it's GameObject-Component by default, which seems reasonable
Just so i can get a better grasp, could you apply this to the situation i'm in right now?
@eternal needle
Specfically regarding an interger number, and a function of sorts
To mean, it sounds like the "abilities" i'm trying to make in ECS would be individual classes, but i feel like i missunderstood
You don't necessarily need ability to be a class; it can be a function. My recommenation was to put abilities into a separate class if you plan on swapping them between PlayerControllers, and then simply swapping the mapping between the PlayerController and AbilityManager class, or what have you
I did suffer from a few issues in Lua, with my god object. For instance, adding anything to the massive array would require me recode a lot of stuff, and every class needed to have the same inputs, so it wasn't very flexible. I assume i'd have similar issues with class inheritance
try not to cringe coder edition haha. I mean it worked, and i was just goofing off in a multiplayer game me and my buddies played, so it served it's purpose
For a character system, i really wouldnt inherit at all. Everything about a character is really just unique functionality you can attach to an object. Like for movement, theres probably some standard things you can do. Lets say, move jump and knockback. The character itself shouldnt implement this, it should just reference another component that does it. This would be composition, you attach a movement script logic to your character. Things may be able to call like
character.ApplyKnockback(whatever) and then the character script could apply that to its movement script. The movement script itself could use inheritance. Lets say things want to move in different ways, one character flies and another cant. Either way the functions are the same, move jump and knockback. Jump in this case might just be going higher while flying
Even the stats system you dont need inheritance, the character script can just hold a reference to the stats. The stats can get all of its information from scriptable objects
I like to make my code in a way where i can fully define an enemy in editor. Excluding the need for unique abilities of course
and even unique abilities could be tailored into that system if built up carefully
Seems like we're on the same page then. I pretty much have everything besides the most basic stats separated into unique classes "playermovement, healthsystem, playermanager, playerclass(parent), defaultclass(child). The player manager assigns the class, and the player movement refrences that assigned class for it's speed stats. That's the way I'm currently trying to make it at least
I already had scriptable objects set up too, the only reason i didn't use it was because i couldn't add the unique code
Why do you have a default class inheritance for your playerclass? Your player should be your players base.
i don't understand, player?
i just meant more of an ability is gonna have to require a new script if its really specific. Unless you really go deep into making a modular system which isnt easy. I guess it is still defining an enemy in editor but theres still one script only used for 1 thing.
For context, WendigoJr is used to using Lua and is not familiar with Unity's style of doing things, so they're coming from a pure OOP perspective
Nothing wrong with OOP being used in unity
So what is playerclass doing, what is playermanager doing?
Never said it was. It's just not a good default approach for their use case.
meh it still is OOP, just we are defining instances of objects in editor vs defining it in code.
public abstract class PlayerClass : MonoBehaviour
{
public string className;
public HealthSystem health;
public float speed;
public float jumpHeight;
public GameObject playerModel;
public System.Action ability;
public System.Action onDeath;
public bool canUseAbility;
public float abilityCooldown; // Cooldown time in seconds
public virtual void Start()
{
health = new HealthSystem(5); // Default max health
canUseAbility = true;
}
public abstract void UseAbility();
}
And what is defaultclass doing that you need to inherit?
public class DefaultClass : PlayerClass
{
public DefaultClass()
{
className = "Default";
health = new HealthSystem(150);
speed = 5.0f;
jumpHeight = 2.0f;
}
public override void UseAbility()
{
Debug.Log("Playing default class");
}
}
scriptable objects here completely replaces the need for this derived classes
Along with attaching abilities compared to what you're doing of defining it in code as inheritance
I usually imagine "object" as a type that stores data and methods, not a game object that seems distinct from manually-defined objects
It's a bit abstract, I guess
As bawsi said, you could just create a scriptableobject that is your "Default" player stats and go from there.
your playerclass could hold a list of abilities that you can assign. Same goes for items, armory or temporary effects. You should write down what type of properties you need on your player that will change through the course of your game
Again i wanna applogize because i feel like i'm going in circles lol, but how would i code unique functionality for each class that falls outside the definitions of the scriptableobject?
GameObject is just a class that inherits from UnityEngine.Object
everything is an object. It would be the same if you defined it like
new GameObject(Stats, Movement, Ability1...);
thats really all unity is doing anyways.
Well actually- let me clarify
I meant the instance of a game object rather than the type
I fail to see the distinction I guess
Specfically just the ability, because i imagine it would be like "summonbomb.cs" with just a few lines of code, which seems inconvient to me to do for every ability, or anything unique
Thats actually desired in most cases
Your scriptableobject wuld just be the container for your abilities. you could add abilities from a sharing class for example and tie that into your stats, how they affect them for example
you would have an abilitiy class that has abstract methods, and inherit from that to create your custom behaviour which needs to fit the methods defined by your base abilitiy for example.
Instances are not types so they can't be treated the same way as an object in OOP. You can't inherit from an instance
In the traditional sense of an "object" being an instance of a class, a GO in a scene is an instance of the GameObject class
Yeah, that's how I view it
why are we mixing up code structure and runtime lifetime here?
I don't know if there was confusion earlier
project worked n dis jus appeared idk wth is dis script
Your IDE should tell you, what is missing. your ListPool is not present for your code at that line
There is some misunderstanding of what instance means here
Of course you cannot inherit from instance...
I mentioned that staple OOP features shouldn't be the default approach to solving a problem in Unity, as composition is pretty much the go-to default problem solving approach.
If you approach solving a problem, subclassing should not be the go-to for most problems.
i didnt even write it and idk its sytsem script
Then bawsi said game objects in the scene are objects in OOP, then I made the distinction above.
oh, its a system one. try to delete the packagecache in library and let it reimport
Because that is correct. It IS an object in oop.
Yes composition is preferable... but your distinction is not really making sense, it is confusing unrelated issues.
Bawsi supports composition all the time though. No one is going against that
where is library folder located
This is better, usually abilities would inherit from some methods. You describe it as inconvenient but consider it the other way around, you would have the capability of writing only a few lines of code and an entire new game mechanic.
just to note this would be completely different from scriptable objects. Scriptable objects literally just save you from having to define stuff in code. For example this is my entire scriptable object code for defining the default stats a character can have. https://gdl.space/wujesiqeru.cs And one method is literally just editor utility to auto populate the stats with 0.
The root of the project folder
You might also try just restarting your editor, if you haven't. Sometimes that can clear a wonky editor state
I think someone disagreed with my statement about traditional OOP and inheritance being a poor choice and I've been locked in a loop of clarifying my statement
I think you may have misunderstood what they said
even more errors after restarting
Probably
facebook try to make anything actually work challenge impossible
Restart Unity again
Did you follow any guide for it?
its a simple download, drag n drop install
i didnt eeven start implemeting it
Try this I guess
??
i dont have any errors
i did that, just impoted da package and errors lol
click that
your IDE should be pointing these compile errors though, unless the error is not from your code
maybe it was made for another Unity version
And it doesn’t work with the one you are using
Just guessing
the screenshots look quite old, maybe its outdated
the issue is i set a variable name wrong, also i dont think ive got my IDE setup right
!ide
follow the steps there
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
• Other/None
ill do later, right now the things its pointing out for me are helpfull
downloaded the newest one
Did you restart Unity? Does it still show errors?
Hey,
Can someone happen to give me a script what changes an animation by clicking on a bottom and this name indicates the animation on the cube?
Or generally help me with the topic?
Did you google it? Unity Button, Click, Animation, Clip?
Would it be wise to overide a abstract function inside my movement script? So lets say i wanted to make a class make a sound when they jump, i could just make a file and then code my unique functionality inside it, hooking into the method i had defined to trigger it, and then possibly refrence that in the scriptable object? I don't know if i'm cooking or this is dumb haha, my brain is turning to mush
Maybe take a break?
Fair
No, no one will give you a script. If you describe what you tried and what problem you have with it, someone can help
I'm really bad what Google is going on. But yes I've been trying for 2 days
this part is really hard to suggest because movement systems are complex. Thats definitely a possibility but usually you'd want some central way of moving and inheriting just to only add a sound would feel a bit weird.
I would do this the other way, have every character possibly play a noise or animation on jump. If you dont attach a noise or animation, it simply doesnt do that logic
yeah, facebook sdk completly fucked up my project by just importing it, i see on forums now its they fault
my ability system is by no means perfect (its actually pretty shit) but one thing is i made it really easy to define animations that play. The exact same logic will be applied to sound
An enum which simply says when to play it, when its charging, when the ability is used, when the ability exits. How long it should take etc
Again, just to get a better idea of what's going on here, could i see the melee script?
No problem whatsoever though if you'd prefer not to
haha, i'm reading the latest hytale blog and they're discussing the exact same thing as we are. very odd coincidence
Its not an easy topic, especially about players with abilities like in an rpg or similar. You have to keep track and know, what your code is doing. So its good, you think about it a lot.
Yeah i wanna start off with something more flexible this time. I all but doomed myself with my last game
this logic is actually on my AbilityBase, this is the part for inheritance. the melee script doesnt have any logic related to animations. I dont mind sharing snippets, its really simple. There is one thing i do backwards for simplicity in how the code is written. Basically on charge up, ill try calling the animation code with AnimationTiming.StartChargeUp and check if it matches the one chosen in inspector. If not, return. Same for ability, and exit ability.
https://gdl.space/rukaladexo.cs
We all been there, thats how we learn 😄 Also using pen and paper sometimes helps before writing any line of code
for the snippet above, I could easily do it like
void AbilityInternal()
{
if(animationTiming == AnimationTiming.Ability)
HandleAnimation();
Ability();
}
i just didnt want to
the script is quite long so i excluded a lot like where i define my fields and the enums but you can definitely figure that part out :p
btw. Do you know when I have 3 levels, but have similar menu, have 'basic' similar elements for each, for instance on the screen. Is not weird create prefab on Level Base object, which contains UI, Coin Manager Selector. You get it? @teal viper
Sorry, I don't understand what you're trying to say. Can you maybe use a translator?
Well, look at this. I have in Level 1 scene such elements as: pause menu, win menu, lose menu and other elements that will be the same in all scenes (levels). Is this how it should be done, to have a prefab called Level Base with all these objects?
It's one way of doing it. Another one is putting the shared prefabs, like ui into a DDOL scene.
how can i fix this issue? all i know is that the number is to high.. but i havent found a way yet to solve this issue.
You can't the number is too big. Unity playerprefs don't support long afaik
hm. is their like no way to convert those numbers into letters tho?
There is. Into string and back
You'd need to save it as a string though
So i have to put int into string and back?
Yes. Or use a different serializer
Consider learning about JSON Serialization and how to write JSON to a file, instead of using Shitty PlayerPrefs
Although you can also learn JSON Serialization and use that to write strings to PlayerPrefs
I have a question, When do you use shaders and when do you use shader graphs. I understand shaders are mainly vertex and fragment. but if i want to make a special effects i use a shader graph. I might also be explaining it wrong
Shader graph just generates the shader code for you.
You use shader graph, when you don't know how to write shader code and are too lazy to learn. Or for convenience
hmmm, that explains it
Then i have a question, I want to make bullets that look like lasers. From there I am guessing it is more of a vfx thing than a material
Depends. There are many ways you can implement it.
The simplest one would probably be a line renderer
In my current project I want the player to unlock multiple 'charges' of their dash ability, and I have them regenerating in update. with my current function it just permanently sets the timer to max, so it's never counting down, but I can't work out how to fix it. If I use a coroutine will that keep getting reset as well?
if (availableDashes < maxDashCount)
{
dashCooldownTimer = dashCooldown;
if (dashCooldownTimer > 0)
{
dashCooldownTimer -= Time.deltaTime;
if (dashCooldownTimer <= 0)
availableDashes++;
}
}
Thank you for your answer. It's enough for me that you give me an understanding of what approaches exist. And I can figure them out on my own
You'd evaluate the available dashes only once (not every frame - maybe when using dash) and reset the timer then. Elsewhere (maybe in Update) would be where you'd count down the timer etc.
removerange second arg at 0 removes nothing?
If you have an issue related to RemoveRange then please share the full context. Nobody knows what you are talking about right now
Sounds like your code has issues
Im a complete beginner, where should i start? also is it a good idea to ask chatgpt for codes?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
ok ty!
ChatGPT is a useful tool for receiving help with individual tasks. However, especially as a beginner I very much advice you dont use chatGPT. It's especially not a good idea to use it for learning.
hi guys i have a question why did w show on inspector but dont show on game?
Looks like you are using SpriteRenderer inside canvas. You should use Image for UI elements, and SpriteRenderer for non-UI objects in the scene
thanks
please explain how to get normal shader in urp why it is gltchy how to remove?
can I use webgpu in unity? if so how do I create a project with it. Need to impress my teacher with something dxd
Greetings from the Unity Graphics team.
We’re excited to announce that starting with Unity 2023.3, the Unity Web Player now provides experimental...
!vc
Unity Version Control
Git
Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory.

hey peeps
so I"m making a card game and I want to queue up all my animations and actions in a way that waits for each to end before starting another one
Thing is, I still want for user interaction to be possible while the animations happen
My friend recommended me to use Coroutines but I also heard of Async
So my question is, which one do I use for the animation in a way that doesn't lock user input until they finish?
Both can be used. Unity doesn't really work good with raw async stuff, but you can await a callback from a coroutine. So use whatever is easier for you in this specific case.
So coroutines won't take all processing away then?
They still share it with other routines like input detection and the like
Because I saw in a video that the coroutine is run in the mainthread
it is, but it doesn't block any other code
Ok, thank you!
In general pretty much everything in Unity runs in one thread
Async-tasks work the same as Coroutines in Unity, FYI
And with new Unity there are Awaitables which make asynchronous programming even easier
Sometimes it can get out of the main thread if you wait for some 3rd party stuff for example
This sounds like two different questions:
- How do I use the new input system?
- How do I add new features to a movement component?
A dash is a dash; it doesn't matter if it's triggered when Input.GetKeyDown(KeyCode.LeftShift) returns true or when you get a callback from the "Dash" action
it's hard to answer that question because my answer would just be "i learned how to do it" 😉
Try thinking about how you'd implement that movement feature completely on its own
so, not as part of a more a complicated character controller
you could implement a character controller script that does nothing but dash
when you press shift, you look at the current movement input
store that and move in that direction for half a second
In addition to what fen said:
Try tinkering with the code.. make the jump higher, try to get the logic thats underlying..
try to code something you've allready seen.. like a jump maybe, without looking too much at the code.. could you get the jump working in a different axis? is that maybe close to a dash?
how could you tweak it to behave like a dash..?
Lots of stuff in the beginning is just "tinkering" and picking stuff up you've seen somewhere.. squash stuff together and see what happens.. just what smaller kids do, they see something, try themselves and see what happens 😄
I kinda disagree don't go through the entire thing I think once you learn the basics from it move on
also I suggest learning about c# if you intend on programming too as I'm new as well I found it helped me a lot
https://www.w3schools.com/cs/index.php this helped me
https://docs.unity3d.com/Packages/com.unity.cinemachine@3.1/manual/CinemachineCameraEvents.html
Hello, can someone guide me to where I can read about how to use these events?
There are no examples sadly.
This is complicated enough that I probably wouldn't use either one. Instead I would build my own state machine for this.
They're UnityEvents, so you do something like:
Unity.Cinemachine.CinemachineCore.CameraUpdatedEvent.AddListener(...);
How would you do this?
This seems wayyy too complicated for a State Machine in my very questionable newbie opinion
Thanks Ill look more into UnityEvents then.
What would that subscribe to? What I linked says you can specify specific cameras.
oh, this is a component
stick it on the object that has your virtual camera and then add listeners as usual
What does it mean for me too be getting this from play console after I just updated it to mention that I will be using advertizing:
1 Error
Error
Your advertising ID declaration in Play Console says that your app uses advertising ID. A manifest file in one of your active artifacts doesn't include the com.google.android.gms.permission.AD_ID permission.
If you don't include this permission in your manifest file, your advertising identifier will be zeroed out. This may break your advertising and analytics use cases, and cause loss of revenue. Learn more
You can remove these errors by updating your advertising ID declaration
Apps that target Android 13 (API 33) without the AD_ID permission will have their advertising identifier zeroed out. This may impact advertising and analytics use-cases. Learn more
the message clearly explains how to solve the problem
And I already added it to my manifest yet it's still saying all that:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.unity3d.player"
xmlns:tools="http://schemas.android.com/tools">
<!-- Add the necessary permissions -->
<uses-permission android:name="com.google.android.gms.permission.AD_ID" />
<uses-permission android:name="com.android.vending.BILLING" />
<application>
<!-- Add the Google Mobile Ads application ID -->
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="some specail code"/>
<activity android:name="com.unity3d.player.UnityPlayerActivity"
android:theme="@style/UnityThemeSelector">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data android:name="unityplayer.UnityActivity" android:value="true" />
</activity>
</application>
</manifest>
But I did what they asked. I set my manifest to custom and edit it to inslude what they asked for
oh
damn the other places are ghost towns. Ok then
hello
'''cs
//
public void startGame()
{
startGameScreen.SetActive(false);
GameObject.FindGameObjectWithTag("Player").SetActive(true);
GameObject.FindGameObjectWithTag("Respawn").SetActive(true);
}
'''
how can I reffer to the tagged game objects without setting an object for them?
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
What's that supposed to mean
so here is how it is...
Whenever start game button is clicked, I want startGame screen to deactivate, which it does.
Then spawn the player and obstacles tagged as respawn
public playerScript player;
player = GameObject.FindGameObjectWithTag("Player").SetActive(true);
instead of this
is there any way to directly reffer to them?
Why dont you want to store your player on Start() for example and then access that in all other methods?
Let me rephrase it:
How can I refer to the
GameObjectwith atagwithout having to serialize a field for it in the Inspector?
It that right?
thank you for translation ^^
In order to reference an object using their tag, you'll have to use the GameObject.FindGameObjectWithTag method
store it in a private field after searching for the tag in start
so field is still needed huh
Surely
Or let it subscribe itself to your "GameManager"(?) , if it is changing because you are destroying it or whatever
You want to force writing unperformant code? 😄
private GameObject yourObject;
private void Awake() => yourObject = FindGameObjectWithTag("YourObject");
okay thanks
Also if there is only one player alive anytime, you can just use the singleton logic to access it
how u write it?
What does it mean?
like a code window
// your code goes here
You dont need to search for it again, when you assigned player once
` copy paste this three times 😉
` <- this symbol should be on the left side of your key 1
hey, if i want to send a long code i need to do it in pastebin?
Yes, for example. I prefer gdl space. !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ok, so i have this code - https://gdl.space/yayocuhapu.cs
it's from a wall ride youtube video - https://www.youtube.com/watch?v=WfW0k5qENxM&t=1s
and i want to be able to not jump on the same wall twice.
i'm on it for 2 hours already trying many different approaches with no avail.
i know i need to store the wall im riding on as a variable and then compare the next wall im riding on to the last wall but the
(wallLeft || wallRight)
is messing me up.
can someone think of a way i can do it?
WALL JUMPING & CAMERA EFFECTS - Unity Tutorial
As a continuation to my wall run tutorial last week, I'm now going to show you how to add wall jumping and smooth camera effects (fov change and cam tilt).
If this tutorial has helped you in any way, I would really appreciate it if you leave a like in return. And you can also subscribe to this cha...
Your Method WallJump or the input check itself should look for the last wall touched and then skip if its not null for example. set it to null if both walls are null (false)
ah, you're asking how to add an extra condition to what you already have
yeah, you can save the wall you found in CheckForWall
that'll be in rightWallHit / leftWallHit
You could also just remember if the last wall you were on was a left wall or a right wall
As long as you can not turn around on the wall 😉
i'll try and update
you might do both!
Although that could make you fall down if you pass from one wall to another
guys how do I check if an animation is playing in an if statement?
using mecanim?
(that is, the built-in Animator)
private void CheckForWall()
{
wallRight = Physics.Raycast(transform.position, orientation.right, out rightWallHit, wallCheckDistance, whatIsWall);
wallLeft = Physics.Raycast(transform.position, -orientation.right, out leftWallHit, wallCheckDistance, whatIsWall);
if (wallRight) currWall = wallRight;
else currWall = wallLeft;
}
so like that?
This would set currWall before you even start a wallrun
so you'd never get to do a wallrun at all
You'd need to set the current wall when you stop a wallrun, I think
so i can try to add another bool to check if i touched a wall before already and set it to true
once wallride for the first time
private void CheckForWall()
{
wallRight = Physics.Raycast(transform.position, orientation.right, out rightWallHit, wallCheckDistance, whatIsWall);
wallLeft = Physics.Raycast(transform.position, -orientation.right, out leftWallHit, wallCheckDistance, whatIsWall);
if (touchedAWallAlready)
{
if (wallRight) currWall = wallRight;
else currWall = wallLeft;
}
}
// in state machine vvv
if ((wallLeft || wallRight) && verticalInput > 0 && !playerMovement.grounded && !exitingWall)
{
if (!playerMovement.wallRunning)
{
StartWallRun();
touchedAWallAlready = true;
}
//Drop if equipped, "Q" is pressed and fpsCam is playing the "Idle" animation
if (equipped && Input.GetKeyDown(KeyCode.Q)) Drop();
how Do I do This ??
I wanna call the drop function if the fpsCam is playing the Idle Animation
So set a bool when it's playing and unset it when it's not. Then just check the bool
but that's what i dont know 😅
how do I check if the fpsCam is playing that animation?
Somewhere in your code you must set it to play
its set to play in another script
so ?
scripts can reference eachother or you can pass the bool via a singleton/manager
Enums and Arrays
If all you're doing is calling AddListener on each button in your Awake method, you can just hook up the events on the Button components instead.
this is for keybind rebinding
cant really use an array
yes you can
actually, this is the perfect place to do so
an array is a single value though
you aren't trying to do specific things with each button
i should use a dict
no, you should make a class that holds a button and a text component
This depends entirely on what you are trying to do though
[System.Serializable]
public class RebindingButton {
public Button button;
public TMP_Text text;
}
now you can serialize a List<RebindingButton>
just a basic keybind rebinding thing
huh
Even better, you could really just generate the rebinding interface from a list of input controls
that might actually be better
why not a struct?
I generate my control lists from my input actions. Each entry is a prefab.
No reason. A struct would make sense here.
I do often use a struct in this kind of situation
so, preference, i suppose?
Yes then probably follow Fen's advice. Maybe you should also apply a special key that is unique to the key (KeyCode could work here) to find it again
I'd argue structs are not suitable to advice to beginners
why not?
it's just not very important here
Agent.speaker?.SaySentence("Death");
will this null check work instead of an if statement, if Agent.speaker is a monobehavior?
what can i do instead that is also short
Struct behavior can be very complex and unexplainable for beginners. It also makes negligible difference here when it comes to performance like what structs would have
When you destroy a unity object, it becomes equal to null, but it's not actually magically turning into a null reference
how is it any more complex than a class
i mean, the main problem is that myStructList[0].foo = 123; doesn't work
other than that it's going to look and feel the same
Rebinding through code will have different behavior
if you know classes, you're already 90% the way to a struct
The struct is not being mutated here.
It's just a bundle of a button and a text component.
Not in this question, but who said that it was purely going to be done through the editor?
any other ways of doing a null check on unity objects, that is short, syntax wise?
"if you pass a struct around like a class, it's like you're making a new one."
explanation done
not that I'm aware of, unfortunately
Consider getting rid of the field access entirely
Yes, behavior that the average beginner would not be aware about 😎
perhaps you should just tell the agent to say something
damn
yeah, so tell them? it's not more complex than classes, it's just different. it's not unexplainable at all
the behavior is also irrelevant for a "bag of data" type
if your "average beginner" can't adapt to structs, then they barely knew classes to begin with
Why tell them when you can just suggest the familiar class based approach instead? Not to mention this is not the only explanation that would explain structs. It's much more than that
It answers absolutely nothing about the question, so it's pointless
familiar
classbased approach instead
literally the same thing
I'd just use a class because it doesn't really matter at all here
If you have two options, go with the more familiar one
This is not a channel for code reviews
we're discussing beginner-related coding concepts, aren't we
i see no reason to bar beginners from using structs
Does it fall under their question?
Hi
no, does it have to?
i asked a question too, yknow.
So why bother changing an answer that works fine and point them to use a more complex system? Structs makes no difference here and suggesting it over classes is just going to make it confusing in the future why stuff suddenly doesn't work they expect them to.
you answered with something i didn't understand, so im starting a discussion
@swift crag @astral falcon just updating, i succeed getting what i want using strings -
https://gdl.space/avoqecoxag.cs
if you wanna check it out
i would replace that with an enum
that way you can't accidentally, say, write "NocurrWall" and have it break
public enum WallState {
None,
Left,
Right
}
This creates a new type -- WallState -- with three values
why bother changing an answer
i didn't? im asking my own question
structs make no difference here
which ive gotten an answer on.
point them to use a more complex system
it's not more complex, and i'm not pointing them to it; im asking why you can't point them to it
WallState.None, WallState.Left, WallState.Right
@swift crag good idea
Your question was answered a while ago then, so let's stop the conversation 👍
but clearly you aren't interested in the discussion further than just pushing your own point, so sure, let's drop it
tf you just said to stop the conversation lmao
what do you want
FYI, to avoid weird behavior you should get your components in Awake, not Start
Awake runs before anything else, and is generally the point where you get your components, unless it's deliberately done
what sorts of weird behavior? 👀
@swift crag actually i dont think i'll use it since it complicates things for me and it works right now. also i am positive i will not set it to "NoCurrWall" by mistake 😄
I guess it's more that when you have scripts communicating with eachother, Awake is the point of Initialization, and Start is where the communication happends. See this flow: https://docs.unity3d.com/Manual/ExecutionOrder.html
Yes, it's only an issue when multiple components are interacting with each other
So when you do the initialization in Start, there's a chance the component reference remains null
Suppose you have this setup:
In Unity it's not guaranteed that one script runs before another, so it could randomly break because of it
A.Start: use GetComponent to get a component
B.Start: tell A to do something that needs the component
If B.Start runs first, you'll get an error
Of course, what you should really do is just assign the references in the inspector ahead of time
setting yourself up in Awake and then interacting with other things in Start is just a useful rule of thumb
you can set it up on project settings though
Yeaaaaaahhhh... I would not really advice that though
There's also DefaultExecutionOrder attribute
You're right though
while playing i'm supposed to click on a stone and the rock will be placed in the inventory. but when there are many rocks nearby, when i click on a single one all of them get picked up. Any solutions please?
you'd have to show your code. but most likely you just need to rethink how you are going about it.
a raycast to get just the one you are looking at is typically sufficient and you just call a method on only that object to interact with it
How are you detecting the click?
yeah so you're just checking for input on every single interactable object and assuming the player is looking at that object while in range. perform the interaction from the component that does the raycast.
If you're checking if the ray hits an object, why not just actually call a function on that object instead of just setting a boolean and let every rock try to guess if they're the reason the bool was set?
Thanks for your help guys i'll look into it and hopefully it works
ok so i have type1 which holds type2, how i make type2 take values from type1 on new() without referencing type1
since i cant put type2 constructor into type1
you cant assign some value without knowing value
you can pass (reference of) type1 instance to type2 stored in type1 or pass what type2 needs, when constructing type2 outside type1 struct/class constructor
You either pass parameters into the constructor or assign the fields from outside
"type1 holds type2" is really vague and doesn't really explain much BTW
It could mean it's a nested type, or there's a field of that type, or who knows what
But either way, you either pass params or set from outside.
thought i can mark parent class to always have parent variable accessible
so type2 extends type1?
If so, type2 can access any public or protected members from type1
You wanna give that sentence another go with maybe some specific examples because I have no idea what you're asking
Parent class implies an inheritance hierarchy, that's something you didn't mention in your original question
You are being too vague
Like I said "holds type 2" isn't very meaningful or specific
It's because they have zero clue what they're doing and are just guessing what words mean
how can i delete a script from an object at runtime>
Destroy
Check the docs:
Removes a GameObject, component or asset.
it can destroy any Object
unity Object that is
components inherit from Object so those are included
i see, thanks
If you call it on an object, yes
but if you call it on a component it destroys that component
You ever notice how the moment you ask for the tiniest iota of clarification they vanish like a dad going out to buy a pack of cigarettes
The "refuses to elaborate further" is real with this one
fun game: destroy random stuff you found with Resources.FindObjectsOfTypeAll<UnityEngine.Object>()
this eventually causes an editor crash
My friend found something stupid to try a while ago. I haven't tested it but basically patching Time.deltaTime with Harmony to return a random float
What could that exactly break
everything that is time-dependent
Everything?
since the amount of time that passe per frame will now be a random quantity
whats Harmony
no, things that are not time dependent (e.g. something that deals damage to you once when you touch it) will behave as usual
it is a tool for patching a built game (uh oh, community conduct violation!)
it's for C# in general, but it's designed for game modding
You could use it in your own game for some stupid things
how to do that
I had a use for it a while ago but forgot what
since when i try create type2 it asks for type1 parameters
Yeah, I use it for editor scripting sometimes, like to hook into editor GUI that isn't otherwise accessable.
Right that was it
I've used it before for Rimworld modding. Very nice system.
but anyway, #📖┃code-of-conduct , 😉
This isn't possible, because Time.deltaTime is an extern property. It has no method body for Harmony to modify.
It's still not super clear what you're talking about... Maybe you're trying to call the parent class's constructor from the child class? You might be looking for the base keyword?
Perhaps provide the information that was requested
I have this code that adds all the movement vectors of a controllers to influence one marker. Why is it if one controller (red) is moving up and the other (green) is moving down, then the resulting movement is orange?
void Update()
{
Vector2 combinedVector = Vector2.zero;
foreach (PlayerInputController pic in _controllers)
{
combinedVector += pic.markerMove;
}
combinedVector.Normalize();
_transform.anchoredPosition += combinedVector * (speed * Time.deltaTime);
Show some actual code and errors so we know what you're talking about
first class holding array of second class and second class should have access to first class stuff
Have you tried logging combinedVector?
Looks like the up/down direction's aren't exactly up or down, so their sum doesn't add up to zero. Then you normalize it which makes it stretch in whatever direction
seems like one or more of those vectors you are combining has a non zero value on that axis
Please provide what has been asked for multiple times
Yeah, trying to make sense, but too vague
i see. how can i avoid this stretching? im trying to make this marker something that users can fight for, but actually using it makes it move in a strange direction as its stretching like you said
What final value do you expect when you add up and down together?
Zero?
basically, yeah
the vector goes in all directions as its coresspending to the joystick
This kind of two way referencing is a bit concerning either way. With more details there is certainly a better way
Maybe don't normalize but clamp the result instead
Though I'm not sure I quite understand the game mechanic here
you know how in smash when you get to map select all players can control a single marker to select something
im trying to make that
clamp makes sense
is it a good practice to use Scriptable Object to hold data that needs to be accessible across the game scenes?
In general, modifying a scriptable object at runtime is a bad idea, because it behaves differently in the editor as it does in a build, which can make debugging difficult. In the editor, changes to the ScriptableObject at runtime persist forever. It modifies the asset on disk and those changes are permanent. In a build, though, it will only modify the SO for that run of the program. Closing the program and re-opening it will reset the values to what the project was built with
ok, thank you
Gone again
👻
actually, no, just writing to the object doesn't write the change to disk!
unless you manually edit it some more in the inspector, I believe
i tested this a while back because the behavior of scriptable objects was driving me nuts
(unlike modifying a material...)
Really? And you're referencing that specific asset, not one made with CreateInstance?
yeah what does it exactly do? Create some temp instance and persists till you restart the editor?
then why do the changes persist between sessions 🤔
because the object doesn't get unloaded
do they still persist between sessions?
I just ran into that issue when I wanted to see if I could save persistent data during playtime to SOs ;p
If you load a new scene and nothing is still referencing the object, it gets unloaded
Ah, okay. So if you close the entire editor without saving, it would go back to what it was
Right
I store some mutable data in ScriptableObjects. I put them in a dictionary when the game starts and keep them there forever, so they never get unloaded
I'm not sure why this winds up changing the serialized data, actually
Neat! I learned something today 🌈 ⭐
Soo, hello! I've been making a clicker game in Unity 2D, and not sure how I can make that button teleport inside an object, I've tried to code it, but ended up glitched in different screen sizes.
show current code you tried
After it ended up like that I tried to make it like this, it spawns inside "Main Camera" but realized now when screen size changes it again glitches
te = "Button has decided to MOVE!";
Vector3 newPosition = new Vector3(Random.Range(0f, Screen.width), Random.Range(0f, Screen.height), 0f);
Vector3 worldPosition = Camera.main.ScreenToWorldPoint(newPosition);
Vector3 localPosition = transform.InverseTransformPoint(worldPosition); Object.transform.localPosition = localPosition;```
are you using an orthographic camera?
also what do you mean it glitches, can you show what happens?
Button tries to move outside of the screen, because when screen size changes, main camera and canvas change positions
Not sure, I don't have my pc with me rn
The z component of a screen position is how many units the position is away from the camera
This is computing a position that's 0 meters in front of the camera
if you could come back later when you have that available that would probably be more productive since it'd let you show us what's going on and test proposed solutions
Alright
I will try later
heyo guys!! im creating a pacman in unity as my first project. i've created all the pacman logic and created the maze using a tilemap. i was working on the ghosts now and in order to perform my a star algorithm, i need to get the tilemap down into code as my grid. anyone know how i can do that?
that's a pretty broad question. the tilemap already holds a grid, what part are you stuck on exactly? referencing the tilemap? accessing the grid?
accessing the grid
I wouldn't consider it broad.
have you checked the docs on Tilemap?
maybe not broad in topic, but broad in that it's unclear which part of the process they need help with
This answer shows how to access all Tiles from the Tilemap. Does it guide you the right way?
Not sure in what form you want your grid to me stored. List? Matrix?
Matrix is only usable if you have a specific number of columns
hmmm i see
This means, you cannot have
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0 0
Only a rectangle form.
Sure, then you can indeed use a matrix
If you're fine with making specific positions null
Those where there are no tiles
yeaaa
How can i check time since a scene is loaded? just learnt Time.time is for application.
https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager-activeSceneChanged.html
no idea but maybe, and start a timer?
or just keep track where it was in Time.time
looks good, thanks
You'll need to store the positions of the Tiles this way:
Vector2Int[,] tilePoss;
if directly from the Tilemap, Vector2Int is also an option
Yeah, exactly
Fixed
public bool[,] GenerateMap()
{
bool[,] map = new bool[tilemap.size.x, tilemap.size.y];
for (int x = 0; x < tilemap.size.x; x++)
{
for (int y = 0; y < tilemap.size.y; y++)
{
Vector3Int tilePosition = new Vector3Int(x, y, 0);
TileBase tile = tilemap.GetTile(tilePosition);
map[x, y] = (tile == walkable_tile);
}
}
return map;
}
smth like this?
Yes, this is great
alrightyy tysmm
I also tend to do extension methods to not parse VectorInts all the time
public static TileBase GetTile(this Tilemap tilemap, Vector2Int position) =>
tilemap.GetTile((Vector3Int)position);
I'll send this in case you need it on some point
https://gdl.space/ufedubihug.cs
Is there a way to separate my class logic from the class, like, for example, creating a custom object that carries the logic when an event happens then attaching this object to a scriptable object (for example, an npc)?
You should seriously try googling more
https://docs.unity3d.com/ScriptReference/Time-timeSinceLevelLoad.html
Allowing me to have an event logic and scripting separately?
you could sure, you can even make them separate SOs
in what way?
I just don't know how to insert the custom logic in my NPC SO, for example
oh wait, I just had an idea
oh thats a lot easier 😅 you are right
Maybe I should create a SO inside my NPC folder then write a class that extends my Event SO, then just attach the script to a variable that will hold that class?
maybe that could work
You can also easily use Abstract classes here and create a different behavior for each and just call it like
"Behavior" then all you do is Execute the behavior
I mean yeah everythin you do is gonna be all code
Behaviour is code. Not sure what you mean
how you piece them together is what matters I think.
This is what I mean
I guess I can do a script that is gonna be located in the NPC folder
well yeah its easier to switch out behaviors if lets say its an SO
That should keep my architecture organized nicely
they all have Execute method or somehing common you can call, but they each do something else. You just swap them
goodluck 🫡
Hey, i just had another question hahaa
What if I need a DrawCard Behaviour but its different for each card, making a different class for each behaviour seems weird
Is there an elegant solution to this?
I guess making a method for each card and putting them on a delegate but that's bloated
it really depends
certain things I just use an enum tbh it speeds up the process for me
i'm making a game after all not some code masterpiece
as long as it works and it works well, it doesn't matter how you do it tbh
I see what you mean
I'm taking my time tho to learn SOLID well since I never did that before during uni
Although in a real project, yeah, just do what's easier/faster
yes SOLID is good but remember these are general guidelines, they are not meant to be followed to a T always
What kind of stuff happens in DrawCard?
Depends on the car
Like what differences do the cards have for example
I'm copying hearthstone so
Every card has a different behaviour
which makes the architecture complex
working on a card game also myself, i see what you mean
they have different behaviors, but that doesn't mean that you need one unique blob of code per card
how can i create an error code? if something happens in my game that isnt meant to happen?
write something to the log file i guess
Debug.LogError?
i'm not sure how an "error code" would be used
Debug.LogError
big red text that plague the user's screen
Lebug.DogError
you can also just create your own exceptions and throw those
if ten cards all make you lose the game when you draw them, you have a WhyDidYouPutThisInYourDeckYouIdiot behavior on those cards
no i mean like, error code 123 or whatever for if something specifically happens wrong in my game
You can keep development mode console going and it'll print the errors in a console
i dunno, make up codes
ohh for like the user?
Make a number for those things and when you get an error log that number
i'd really just show a coherent error message
make a const of error codes or something then use a dictionary to print out what they mean
yeah
why do you need an error code when you can just use a proper message? error codes fucking suck because they don't really convey anything useful to the user to know if they fucked up somehow
they mostly just take you to weird malware distribution sites
I want to have a flexible architecture
or mean nothing
idk i just wanted to know if it was possible 😭
Yes, that's my point
Of course it is
You re-use simple behaviors.
Debug.Log(1)
is X possible
Yes
the default of any question is usually . yes
Can I answer a non-trivial question about a Turing machine in a finite amount of time?
so, instead of making a class for each card, make a class for each behaviour instead?
Correct.
sure, but the codes are arbitrary so you just make them up and log/display them just like you would a regular error message. so the proper message is the superior option
You may still have behaviors that are only used by one card
Interesting
(just like how MTG has rules that are there for a single card)
Now, architecting this isn't trivial
It'd be a useful place for [SerializeReference]
i see. I'm going to make a singleton prefab for a UI element that creates toasts for errors/info, which is why i wanted to ask
I have a bunch of places in my game that need to "score" things (e.g. decide how much an entity wants to pull a lever)
You probably want the code internally so easy to lookup in a dictionary thats hold the actual meaning of the code maybe ?
I use [SerializeReference] to store (nested) scoring methods
If you remember, this is what I had suggested to you a while ago. What, like a couple weeks ago? My sense of time is off during finals, but it was a bit
That is composition
And it be strong
just use a proper error message, you'll save yourself a lot of time and headache so you won't have users contacting you like "i got error code XYZ what do i do?" and then you have to go and look up the error code yourself because why would you have them memorized
Have you ran into any issues with SerializeReference in unity 2022+?
In 2021 I've had prefabs with SerializeReference and they got corrupted after some refactoring
I remember it, Aethenosity, it's just that I'm doing a completely diferent code, before i was using delegates and built-in methods for everything, now I"m trying to make my code more SOLID
So i'm tripping a bit on concepts still
If you change a type's name or assembly, existing data will break if you don't correctly annotate the class
The MovedFrom attribute lets you tell Unity what a class used to be named, or where it used to be found
I have used this to refactor before
true 😆 thanks
This happens because it's not serializing the GUID of a script asset -- it's just writing down the name of the type
Wait I swear I was looking for something like this but didn't find
Like FormerlySerializedAs but for types
Undocumented too, ofc
boing
Okay thanks this will be helpful
the alternative is to just rewrite the YAML lol
If you do this, you'll need to re-serialize all of the assets before you can safely get rid of the attribute
Gotcha
private void buildBranches() {
float angle = 180, angleTwo;
List<float> inputAngles = new(), outputAngles = new(), angleRatios = new();
for (int i = 0; i < 360; i++) {
angleTwo = Geometry.angleBetweenVectors(extrude(Vertecies[4]), extrude(Vertecies[4], i)) * Mathf.Rad2Deg;
inputAngles.Add(i);
outputAngles.Add(angleTwo);
angleRatios.Add(i / angleTwo);
}
printList(inputAngles);
printList(outputAngles);
printList(angleRatios);
}
private Vector2 extrude(Vertex v) {
Vector2 dir = v.position.normalized;
//NCvertex(dir * 2 + v.position).connectTo(v);
return dir * 2 + v.position;
}
private Vector2 extrude(Vertex v, float angle)
{
Vector2 dir = Geometry.rotateAroundArbitraryCenter(angle, v.position.normalized, v.position).normalized;
//NCvertex(dir + v.position).connectTo(v);
return dir + v.position;
}
// In Geometry Class:
public static Vector2 rotateAroundOrigin(float theta, Vector2 dir) {
theta *= Mathf.Deg2Rad;
float x = dir.x * Mathf.Cos(theta) - dir.y * Mathf.Sin(theta);
dir.y = dir.x * Mathf.Sin(theta) + dir.y * Mathf.Cos(theta);
dir.x = x;
return dir;
}
public static Vector2 rotateAroundArbitraryCenter(float theta, Vector2 dir, Vector2 ctr)
{
theta *= Mathf.Deg2Rad;
float x = (dir.x - ctr.x) * Mathf.Cos(theta) - (dir.y - ctr.y) * Mathf.Sin(theta) + ctr.x;
dir.y = (dir.x - ctr.x) * Mathf.Sin(theta) + (dir.y - ctr.y) * Mathf.Cos(theta) + ctr.y;
dir.x = x;
return dir;
}
The attached image shows the relation ship between the desired angle (x-axis) and the actual resultant angle between the extrude(vector) and extrude(vector, angle) (y-axis). I don't understand why there is such a large difference between the intended result and outputs. There could be something I'm missing with regard to the rotation function, or something else entirely. Any help woul be appreciated, thanks.
instead of doing the trig yourself, you can just use Quaternion.AngleAxis to create a rotation
that'll make it a bit more concise, at least
see also Vector2.Angle
Do you think that will fix it, if so, why?
No, but I just try to not re-implement what Unity already gives me!
(and there could nominally be an error in your rotation code, but it looks okay)
also, I believe I see the problem
Vertecies[4] is a point at, say, [3,0]
Suppose you extrude by 1 meter to get [4,0]
Then you extrude by 1 meter with a 90 degree rotation to get [3,1] (let's say that's a counter-clockwise rotation)
The angle between [4,0] and [3,1] is not 90 degrees
you wound up with these vectors
The angle between [4,0] - [3,0] and [3,1] - [3,0] is 90 degrees
I have also tried adding the direction vector pre rotation to the vertex's position and then rotating about the vertex, but that just makes a cool circle in the middle of the shape
Your rotation is fine, but your expectations about the resulting angles are wrong
(er, imagine that went up to [3,1], not [3, 0.5]...)
Without creating another script how do I avoid the game object being overriden by the another door using the same script?
private void Start()
{
// Scene setters
previousScene = thisScene;
thisScene = SceneManager.GetActiveScene().name;
if (thisScene == "KawagishiScene" && hasEntered)
{
player.transform.position = doorPos.transform.position + offset;
Debug.Log("doorPos: " + doorPos);
}
}
what is doorpos
doorPos is the exterior of the door
I manually set the door position with an offset to avoid colliding with the entrance again
well you should only add the player when its relevant to the situation
eg if player went in that trigger, it stores player as the one whos in the trigger
if it leaves then the reference should be maybe null so u can return early when null.
or make a bool that only goes true when player is near it/intrigger of that door
I don't understand what the problem is.
Okay, thank you
well they all have player
but these are two separate doors
i don't get it
if they all have a player reference then they'll all try to set the player's position, I guess
yup. either kill the reference when not near or make a simple flag for when is in that building
You need to indicate which door is being exited from
One option would be to give each door an ID, and to have a static field that stores the target door's ID
I remember talking about this with you a few weeks ago
Yeah I just started trying to fix it today, sorry
Or let the player decide where to go instead of moving the player from the door script. As you know what door the player entered, you should have a reference to the door already or like a synced door in your next scene preferably
Is Building not its own class?
would make it so much easier to just store the Building/door it currently "belongs" to
or otherway around, store door /building object in the player
yes, having the door yank the player over to it sounds very weird
Thanks for the hints, I'll see what I can do
fun fact, this was the advice provided to them over a week ago when they were first asking how to do doors and they decided to do something different anyway
oh lol i see you mentioned that nvm then
Hi, I'm a programmer, not too advanced but neither too bad, kinda in between, im currently pursue a degree in CS. That's my background, now, my question was regarding starting as a unity/unreal engine dev, I would like to start with android games and eventually javascript games(I suppose you'll have to use js for that). So what books/sources do you recommend? I still don't know C++ nor C# yet, but I usually learn fast and kinda know C, and do know java. So, any recommendations for learning C++/C# fast for game development is welcome as well.
y javascript game ?