#💻┃code-beginner
1 messages · Page 433 of 1
np! literally watched it a few days ago to solve a problem, just ignore the part where he links the turret rotation to the crosshair
you can make a list of functions . Though I have no idea what you want to do with the switch, you can just use a switch if anything
But with enum, we can just put some names but not directly functions
I do a scriptableObject to create my weapons and I want to can choose what function of the weapon we will use it with, like the bowattack or the magicspells
Having a tough time understanding the difference between Move and SimpleMove for character controllers, despite having looked at the documentation. Can anyone help paint a better picture?
Hi all! I'm currently attempting to create a first person camera. Though it functions, I find that in-scene objects suffer from a sort of jitter movement. I've looked through different tutorials posted on Youtube, however none seem to work. If anyone could link a video or suggest a solution, that would be awesome!!
My camera's code: https://gdl.space/ekupenuxag.cpp
My player movement script: https://gdl.space/ahacequkox.cpp
SimpleMove automatically applies gravity, is framerate independant (I.E. applies deltaTime), doesn't support verticle movement, but is simplier and easier to use than Move.
Move requires you to apply gravity and Time.deltaTime, supports jumping and complex movements, and all round better control over your player character.
However, move takes more effort to code. :D
Move() is the best.. coding in ur gravity isnt hard
u just add a simulatedGravity to the vector
Gotcha, appreciate it!
Also, I went and made my camera a child of my player and I also get the jitteriness you're getting @rare socket
Ooooh. Thanks for the heads up!
What are some good ways to check if a player is on the ground (assuming character controller is being used)?
CC has its own built in Grounded
most people like to make their own
raycasts, trigger colliders, checksphere etc
the builtin one is good enough for basic stuff
Huh, I never knew that. Any idea why people would make their own? Any undesirable things about the built in one?
i haven't found anything that stops me from using it
some say its less than accurate
Hmmm. Will take a look at that
basic characterContoller.isGrounded
there was an issue.. my headBob.CameraRebound() method shuld get called when the player lands.. in my head it made sense to set the wasGrounded bool @ the end of hte update loop.. but that didn't work.. so i had to set wasGrounded on the first of the frame.. (which in my mind didnt feel right) but it works out just fine..
could be issues like that that cause ppl to code in their own groundCheck.. but as long as i can work around little issues like that i'll keep using the cc's ground check
Interesting. Yeah, looks like I have some playing around to do
have fun 🍀
private void OnDrawGizmos()
{
if (Application.isPlaying)
{
var gizmoColor = characterController.isGrounded ? Color.green : Color.red;
Debug.DrawRay(transform.position, -transform.up * (characterController.height/2 + 0.2f), gizmoColor, .1f);
}
}``` i also use some Gizmo's DrawRay to visualize it
(green w/ its grounded and red when its not)
helped me when working on it (my jumps and slopes especially)
characterController.height/2 + 0.2f i just guessed the length..
how do i round floats
are u actually rounding the float? or do u just want to display the float as text (with a certain number of decimals)
If I have an Inventory and in one of the UIs I only want to show ONLY slots that contain specific types of objects is it okay if I instantiate the maximum number of slots in my inventory in each UI and then setActive ones and others no???
or is it a better way to do It?
I have an abstract inventory which holds ALL the objects but I want specific UIs that show specific types of objects
suggestions are accepted
It is not an Abstract class but it is a List that isn´t seen (it is just NOT Viewable). This class separates all of the objects in the Main Inventory (which is a class that contains a list of all the objects the player has) and holds them in slots of 30 items max.
You should really just show code or what you're specifically trying to display. A lot of this doesnt make sense.
All I got from this was you're trying to display stuff and are asking if you should use setactive. Which yea would let you show objects by setting them active
My idea is to have multiple UIs that show the state of the inventory, however, I want some of them to SPECIFICALLY show the objects of a certain type (tools for example)
And I want them to be expandable, for example, if I have 2 tools I want it to show 2 slots that contain tools, same for 1, 4, 6, 2...
Again, this doesnt make sense. You want what to be expandable.
Sounds like you want a filter, in which case you'll need objects to have some sort of grouping. Like an enum, scriptable object, string, or whatever. Just something to group it by so you can go through and see if it's under the filter
You can use setactive I guess if your UI automatically adjusts based on active UI elements.
I want the UIs to be expandable
What is the best way to do it?
a UI manager.. thats controlling what gets enabled /disabled
thats my go-to.. id like to see other suggestions tho
yeah, but is the enabling/disabling method ok?
for UI ? sure
yeah, just to show slots or not
I find the concept of state machine very difficult, if you know any sites that explain it well, I watched a course on Udemy
and i don t understand nothing
Folks I have participated in the 48 hour game jam. I worked for 12 hours till now and all I have completed is Player Input, Idle Run Jump Animations and little bit of Rigging, Movement, Aiming, Crosshair for a 3D game
How would you judge my speed?
my UI manager enable and disable Graphics..
the logic and stuff remains on the Component
shouldnt affect the logic any.. unless u need it to
okay, thanks a lot
from scratch thats not too bad
i recycle stuff for game-jams.. i'd have most of that in my backpocket
this is my 1st game jam, I have experience in creating 2 original 2D games
no worries.. its good to even try out gamejams
I would say I am using imported assets and animations.
from kenney
Mostly video tutorials are shit. What part dont you understand though?
Think of the animator if you've used it, it's just a way of running certain logic when you want. The animator is a bit more advanced as it gives you a way to define what state can happen next, and when it can happen. That's about it
Yeah I wanted to because I suck at doing something really fast. Mostly i get stuck making things perfect, especially the mechanics
game-jams aren't gonna end up perfect
Keep doing things over and over and eventually you'll get faster, keep at it and good job
best to just try to get ur mechanics.. and bulk of the game..
polish the last few hours
games aren't gonna end up perfect either 😸
facts lol
I got 20 hours left, and have AI to do, with some sort of object pooling and level design... Let's see how much I can bring to the table
yeah hope so
Incorrect, E.T. is a perfect game
source: land-fill
perfect for trash
helps motivate me tbh
i know they had technical hurdles to cross
i just like to think they gave it their best.. with Good tech
and im just a better developer 😈
To be fair to them! Resources are far more abundant today 😄
🤫
i kinda miss when everything was awe-inspiring no matter how simple
now its like "meh, thats been done before.. nothing special"
yes
Imagine creating something unique to you but you see the whole world already way ahead of it
i'm having issues with singletons, what am i doing wrong?
i didn't know it was possible to have a nullreference for this
this is not the file your error originates from. what is line 12 of TileColor.cs
so the reason you are getting a NRE here is because you are trying to access the singleton before it has been fully set up. Don't access GameManager.instance before its awake method has run, to ensure you don't you should not access the instance property until Start at the earliest
yup, sounds accurate
Why is the short hand for null pointer exception NRE and not NPE 💀
Because NRE is short for Null Reference Exception
because C# uses references not pointers
Oh yeah that's right haha, I'm used to work with C
which are, basically the same thing, it's just a C# reference is not a pointer to where you think it ought to be if you come from the C world
yes I am aware of the similarities of pointers to references, but references are not pointers, though they use them under the hood. i would think you of all people would be super pedantic about that sort of fact
I'm just trying to make it clearer to someone coming from a C world, not overwhelm them with technical information
I don't understand the logic of this code, I watched a course on Udemy, I can barely keep up. That's all I wrote and apart from the fact that I didn't understand anything, the code doesn't work anymore, my status doesn't change https://paste.ofcode.org/bLWE285Hz85PbcCtwEann3. if somebody help me to the code and make a logical explication. Thx
Hi, I develop my weapons system and I do this script for the ScriptableObject (Item is a ScriptableObject)
And I call it in a script on my Player gameobject
Scripts :
https://gdl.space/obonoboret.cs
But when I click on my right click, I have this error :
Weapon+BowAttackBehavior.Attack () (at Assets/Code/Scripts/Items/Weapons/Weapon.cs:61)
PlayerDamage.Update () (at Assets/Code/Scripts/Player/PlayerDamage.cs:32)```
Why ?
I don't really understand all 😭
But when I don't understand some code, I put in within an IA like ChatGPT or blackBox.ai and ask it to explain me. It works well !
BowSystem.instance is null. are you certain it has been assigned to?
I need obligatory to assign it to a gameobject ?
it likely needs to be assigned an instance of BowSystem because i'm assuming it is part of the singleton pattern. if it is null then trying to access any of its members, like that ThrowArrow method is going to throw a NullReferenceException
No it's not a part of singleton pattern :|. I just let it in my folders of Unity and assign directly the prefab of the arrow
huh?
Maybe I don't understand your question 😭
Please dont tell someone else to go use AI to learn. You might as well not have wrote anything there
I didn't ask a question. i told you that you need to actually assign something to the BowSystem class's instance variable
just like you are for your other singleton the PlayerDamage class
Yes. It must be on a gameobject
Have you debugged anything related to it? Like adding debugs where you are changing states
I don't very understand
What I need to assign to instance of the class BowSystem ?
BowSystem is clearly meant to be a singleton (this is extremely clear even though you haven't bothered to show its code). you have another singleton that you have shown called PlayerDamage. look at how you set that up and do the same for the BowSystem
Because that is how the singleton pattern works
How could you access BowSystem if Instance is not set, with the way you are trying?
When I don't very understand a little part of a program or just a function, I think it's not very bad :/
But I set it with instance = this; no ?
Either way, do not suggest it. That is against the rules here. People know about it, there is NEVER a reason for you to suggest it
#854851968446365696 #📖┃code-of-conduct
Hey, could someone help me out please? I have a button which covers whole screen horizontally, and when I click it a create function is called, which takes the mouse position, and creates an object (action) with that value. Then a line is created, which takes the same position, and is spawned right under my cursor. The thing I'm having trouble with is that I want to connect each object with each line, so that I could change the position in the object, and the position of the line would change respectfully. The initial idea was that when a line is created, I could click on it, a "settings" menu would pop up, and I could change each value manually through there, but I can't figure out a way to parse the values between an instance of an object (action) and a game object.
Sorry, I just wanted to help him 😭 . But i'll don't suggest it also.
But I don't see it's against the rules to suggest use an IA for it in the rules of the server
problem w/ AI and learning is you don't know when its wrong.. or telling u some stupid ridicilous thing.. then they'll end up back here trying to fix something the AI can't anymore
Hey
and you may not be around to help fix it.. (then guys that never suggested using it are stuck trying to help them sort it all back out)
(And at that point humans probably can't either)
lol. trash it 😄
nah, we'll just ping Magico every time someone posts AI code
🤣 saucy..
I don't want it 😭
Okay I see
who would? 😄
I just started a month ago so for me, AI for it was good
then be very careful of the advice you give
if it works for you thats great 👍
But now, I know it's not very good 🙂
I have a list items. I want to make a method that takes a value and adds it to the list, then returns it's reference, so that you can delete that item later. How would i do that?
why would it return the reference if you are passing that in as a parameter?
a simplier case is when it returns void, and i just delete by value. But there could be problems with that
you mean return the index
if it returns the index, and then some items are deleted from the list elsewhere, wouldnt it become wrong?
How bad would it be to spam approximately 360 raycasts to check all around a player?
bad
I need to add the value to the list then delete it.
Gotcha, will do box/sphere then
yes but you are passing the value into the method so you already have it when you want to delete, so why return it?
right, i just overcomplicated things. i know how to do it now
the yellow line is the one created by clicking on the button, all the red lines are there just for the reference of position I needed when creating this, and the second picture is the function ran by clicking the said button
if there's any more info I need to provide please let me know, because I'm really stuck here
you probably want worldPositionStays=true on your SetParent
and, please dont use classes like Action, they confuse with System.Action
yea I figured
I need a better name but I cant come up with it lol
how would I use that?
it's a parameter of the method
yea ik, I mean like how would that help me connect the object to a game object
sorry, I just thought you were having a problem with the position
oh
well sorry if I my description confused you lol, I was just trying to explain everything in a single message
could someone help me out with rotating 2d objects, im new and it seems confusing for me. Thanks
why is my text so choppy
i just use AngleAxis w/ transform.forward
is it TextMeshPro? or Legacy Text
text mesh pro
i just spawned it and it was choppy
and whenever i mess with the settings it doesnt help
theres no aliases tab
this all i got
no rendering tab either
that first setting guy mentions is on the camera i believe..
the other settings mentioned down the page are on the actual TMP material
TMP is typically pretty smooth everytime ive used it...
unless it was a bad font.. or a low quality atlas texture
but i see ur using the built-in LiberationSans font.. (that font isn't as smooth as the others i tend to use.. but i dont think ive seen it as jaggy as the example you shown)
You ought to show the inspector for that object
i changed mine to /Mobile/ shader to test.. and that doesn't make mine jaggy either.. soo not that either..
ya, possibly something im not seeing
Why are my tree's like this when built and ran but not in the unity editor
something something shader keyword
Is this code related?
I mean i dont really know where else to ask
alright thanks
Or #💻┃unity-talk if you're uncertain
But definitely where spawn has suggested
my guess is the terrain shader u use for the tree's isn't being built over to the standalone correctly
looks like they're using an unlit shader or something (hence why all the tree's are the same color) no shadows*
w/ some PPFX grain/dither on top 🙂
question about how serialized fields can be set.
I am using a dear imgui package for unity and it needs a script attached to objects in order to render. That script has several serialized fields to setup the rendering.
If I attach this dear imgui script to an object in the scene some of these fields are prefilled with defaults. Yet when I search in the code for references to the field there are none. So I am guessing there must be some other thing going on? The reason is because I don't want to have to setup this component in every scene myself, I would rather just do it once from code
Maybe those fields are private-serialized.
they are all private yes
i mean you can have dontdestroyonload and carry the whole canvas with you
along with the script that has the setup
using external IMGUI with unity in 2024 is quite frankly a strange choice
but go ahead
yeah but e.g I want my managers which are singletons spawned when they are called to render imgui stuff for debugging. There is nothing for me to setup
I have been using imgui for a long time and have no desire to switch to something else
unity already has imgui too, if it hasnt been deprecated yet
You wouldn't be able to access the members through code if they're private - assuming you're attempting to do so through a different script.
see Unity's OnGUI, you can use stuff like GUI.DrawTexture
even less setup required
should follow imgui standards too
I am just trying to create the script on an singleton object using AddComponent<DearImGui>()
I fill those first two fields after I created the object. But those other three fields at the bottom are empty when I just create it from code. Yet when I drag and drop the thing they are filled.
how do i check if a rigidbody has stopped?
you can check if a rigidbodies velocity is 0
how can i check if currently no children selectable objects are selected?
I'm unsure what the question is here, just see if it doesn't have a blue highlight?
i mean ui buttons and stuff mainly for controller support
How do I change the Position of my Player without them loosing there momentum? (2D)
This might help
In your movement controller, sync your transforms before moving
Is it possible to acess a Script from another Scene?
Actually hrm, I don't think it will. It'll flush the momentum.
For some reason tho the vertical momentum stays
well to answer my own question. I just load a prefab for my singleton that already has the imgui script configured. Works like a charm and I don't have to setup things in the scene
if its a monobehaviour im pretty sure its not. but why would you want that?
just asking, incase i need it somewhen
you can take objects with scripts into another scene with dontdestroyonload
but you cant directly call a monobehaviour that is in another scene
@pine aspen @shell herald
To be clear. No, you cannot load an object from a scene that is not loaded, because it simply will not exist. Everything in a scene is destroyed when unloading the scene.
However, you can have multiple scenes loaded at the same time, and you can access a gameobject from another loaded scene the EXACT SAME WAY you access on from the same scene
DontDestroyOnLoad IS a scene. It is a special scene that doesn't destroy everything in it when a new scene is loaded non-addively.
It works nearly the same as additive scene loading.
why i can't see the camera limits?
Looks like you have gizmos disabled in scene view (last button on the scene view toolbar). This is not a code question.
thxx!!
is that disabled by default now?
idk if im crazy but i can remember old versions not being like this
hello im new to unity, can someone teach me how to move rigidbodies?
currently I have a character controller and rigidbody attached to an empty called the FPScontroller, and the main camera is a child of this empty. I have another sphere with rigidbody attached to it, but I cant seem to push the sphere by walking towards it.
I think the main reason would be that I dont have a 3D object attached to the FPS, I trial and errored adding a capsule+rigidbody as a child of fps, but weird stuff happens even if I lock the rotation of the capsule
It's a game object, not an empty. If you're using rigidbody movement, you shouldnt have the character controller component as well. You either move via the cc or the rb. If you want unity physics (objects pushing each other, colliding, etc) then stick to rb and use AddForce or assign its velocity
sorry can you explain more
I am like new new to unity, I just followed youtube tutorials to get to this point.
just realized this isnt code related
About what specifically?
Eh it can be depending how you set it up. Did you figure it out?
So the issue is that you're trying to edit a collider on an object right?
or do i need to add something somehow manually?
on a tile map specifically
i want to change its collider type´s effect to grid based instead of sprite based
explain why rb and cc cant coexist
and what specifically should I do now to be able to push stuff. If you are saying rb and cc cant coexist, can I move stuff with player using code? How exactly would that look like
Character Controller is specifically designed to allow easy mvoement without a rigidbody. Adding a rigidbody to it means it's going to be fighting against itself unless you micromanage which is enabled at any given time
Basically, it's self defeating and combining them means you have a design issue
if you want physics based movement, you shouldn't want the features a character controller provides because they're simply out of scope, and vice versa
It is not disabled by default now, no
I remember explaining that to you multiple times in the past
Edit: no, slightly different
#💻┃code-beginner message
they are both different methods of movement. They can co-exist, you can have a kinematic rb on a character controller if you want other stuff like physics messages OnCollisionEnter (and the rest). But you shouldnt be moving by both
Look up tutorials for rigidbody movement,
How exactly would that look like
this is something you'll have to try out, use the docs and guides to help you. If you have specific problems with trying then ask that
Haven't used tilemaps, but you can just check in your scene whether it has the appropriate collider component or not
If it's present, all you need is to get a reference to it (either by drag/dropping to your script in the inspector (preferable) or finding with one of the appropriate methods (slower)
create a public or serialized field for it in your script and refresh, then drag it there.
the thing is i dont have this on my editor
i cant find it
i know how to acces via code but i do not have this component/asset
or if i have it im blind
zoom out a bit, is this still about trying to change the collider type?
that screenshot is from the unity manual
Im having a problem. In my player theres a variable. public TMP_Text popup; and in unity i assing the script with the text but as soon as a start the scene my script unassigns it.
i do not have that in my project, or if i have it i do not find it
It's just showing you an example then, you're not going to have the assets shown in the manual
but i do not know how to add one like that
if it gets unassigned, either the reference gets lost or you are trying to assign it on awake/start but its not finding anything. show code/your setup
I'm not sure what type of asset it actually is from what you're showing. But generally just right click in the project view -> Create -> 2d -> Tiles if its a tile
ik you guys always like the code sent to you on some website? how do you want this?
!code
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
i found it, but this didnt solve my problem :((
https://gdl.space/malaneyulu.cpp shouldnt this activate if i enter on the tilemap collider?
you are trying to assign it on awake/start but its not finding anything
if you're assigning it in the inspector, then only call GetComponent if its null
Thank you very much
if that fixed it, then you need to check in the editor for where your component actually is relative to the script
wild guess, it's probably in a child
i figured out my problem
GetComponent will only get the component if its on the same gameobject as the script, if you want to get a component on a different object you need to call getcomponent in that scope instead
it was as simple and dumb as one can think
i forgot to add a collider to the player
💀
Also, ignore this if you don't care, but I'd strongly recommend using a standardized naming scheme for your code, it will make things MUCH easier to maintain and read at a glance in the future.
Im confused what do you mean? like camel casing?
To start with yes, also reconsider the names of your fields so they relate to the type. Also multiple declarations are allowed in c# but generally very strongly cautioned against as they're relatively messy
vector3.magnitude can't be negative, right?
that's right iirc
worst case scenario is to just try it with a quick test script and find out
The length of the vector is square root of (x*x+y*y+z*z).
like to break it down. In this declaration why is the first field a lower case verb, the second a capital noun and the third a lower case noun despite all being the same scope and type? public GameObject carrying, Player, furnace;
been messing with mesh generation, started with simple a voxel, I keep seeing videos where people have like double or even tripple verticies on the corners. I'm guessing here that the GPU just don't give a shit about that and only cares where's the triangle I need to draw one.
i was in sped english so often i never really look at small details like that also idk what a noun or verb is. yk?
It's important to focus on details, these aren't small things
Someone looking at your code (or you when you're tired) can easily confuse your 'carrying' gameobject with a bool, since you named your bool 'holding'
Inconsistency creates spaghetti down the line
ohhhh i get what you mean now
Also, this public bool holding, nearFurnace =false; isn't doing what you think it is
thats not done yet
false is the default value of a bool, so the assignment is pointless (though totally fine) but when you do it this way it's ONLY assigning nearFurnace to false, not holding. holding is only false because that's the default value, not because you're assigning it
oh i see
if you want both to be false then you should either not declare anything or (if you want to visualize it) do public bool IsHolding = false, IsNearFurnace = false;
i just had a look in the inspector while trying it and the game works fine with it. I appriciate the help im putting all this into consideration thank you bro.
The game works with it because it's technically valid and does nothing
Try doing it with true and you'll see what I mean
the bool will be false even if you don't include = false
because all bools are false unless set otherwise
bool isHolding = false; is exactly the same as bool isHolding;
The way you have them set up atm, you also can't trust them to actually be false
oh so putting it as set to false is pointless and accoplishes the same thing if i did set them to false in seperate lines. ok thank you
Since they're public, their actual value will depend on what you set in the editor
which is false i see
if you need these to be false, you should either be setting them as private/protected, setting a DoNotSerialize attribute or using a property
For example, let's say today you edit the prefab this script is used on and tick the bool as 'true' in the inspector. When you go to debug later, you're going to probably just look at the script and see that it's set 'false', not realizing that in actual gameplay it's going to be true.
noted. Thank you
In general, everything should be private unless it needs to be accessed from another class or inherited
it'll save you a ton of time later
You can make your update much less stressful to manage as well by using a coroutine
Hey guys
I have this Camera and the Boxes you see are the borders of my level.
I can't scale the camera to display the entire level for some reason, it becomes larger. Do you guys know a way?
Can you reword that?
The Camera can only show these many boxes at once, I want it to be able to show all of them
I have a Following Camera script but I would also like a Fixed Camera
Have you tried modifying the camera's "Size" field in the inspector/.orthographicSize in script?
(assuming you're using an orthographic camera, that is)
Which property are you modifying to scale it?
Size as mentioned by mr raccoon
Like scale?
Ah.
Anyway, I think I'll go with the following camera. May I ask your opinion on something?
is there a https://docs.unity3d.com/ScriptReference/Texture2D.SetPixels.html equivalent for 2d float arrays? trying apply a 2d float array of numbers 0.0f to 1.0f to a Texture2D
Just check to make sure. Orthographic size is vertical based.
is there a more optimized way of doing bullets "hit you" than Collider? because im doing a bullet hell and there are a lot of bullets, dont know if the game will be able to render it
Collisions won’t be your issue
Don’t use unity physics for a bullet hell!
so i should use .translate or something like that?
They’re fine, don’t over complicate it
Use an object pool for instantiation
And set all the bullets in a layer that ignores itself
what is an object pool?
im a bit confused by this. this always returns true even if i dont have any of the required materials exept 1.
Definitely no
Instead of instantiating a new bullet every shot, create a pool of hundreds or thousands when you start the game and recycle them
Enable and disable instead of instantiate and destroy
Instantiation is incredibly expensive relative to nearly anything else
Use your own logic for bullet movement and physics
You loop returns true at the end of the first iteration rather than after all items have been checked. So all that is necessary is that the first item in the array is true
You can use OnEnable and OnDisable to handle state if you want to be quick about it, otherwise you should set up a generic object pool class + an interface for poolables so you can recycle it throughout your projects going forward
Which one looks better? A Fixed Camera like this? Or a zoomed in Following Camera like this? Your feedback is greatly appreciated 🙏
i only am familiar wih monobehaviour classes at the moment
how do i change that?
Bullet hell may be too much at the moment then.
Do some small games and learn the bits and pieces you'll need as you go.
Prototypes are great too, just doing one system at a time
#archived-game-design or #1180170818983051344 (it depends on your game) both options are good.. both work
Move your return true to after the loop, such that it only does so if no item in the collection was false
i made a movement system and that looked cool, but yeah it was fairly optimizable,
i want to make a very simple bullet hell
Thank you. I may use both in the end.
like this ?
Just think through the problem and take a stab at coding out a simple solution. it's not terribly complicated if you break it down piece by piece
which i nearly have already finished, but the last thing im doing is the colliders and thought it would consume a lot
Yeah - the log is inaccurate now, but the logic checks out :)
you're going to have a collection of disabled gameobjects. Other classes can request an object, in which case you enable and return one if one is in your collection or you create a new one and return it. Other classes can also return an object to you, in which case you disable it and store it.
Don't worry about optimization this early
a collection as in List?
It doesn't really matter, personally I'd use a stack but whatever floats your boat
yeah but im a bit obsessed with that, im scared to even use more than 50 raycast 😭
which i know are like nothing
but it seems to much to my eyes
lmao
You have to get over it.
Overoptimization causes more problems than it solves
it's better to get something down and working, then iterate on it
Then JUST learn object pooling (so many guides online) and do a simple one
Don't worry about optimizing
Obviously don't throw caution to the wind and do something absurd, but don't get action paralysis from worrying about a few nanoseconds here and there
Raycasts are basically free....
A couple thousand a frame is cheap
i use tonnes
The ObjectPool collection unity has built in may be best
i know, thats the sad part
Well, get over it then. Easy as that. You need things like that. Optimizing always should come last
Some simple things, sure, consider at first, but as we said, raycasts are basically free, so limiting them is NOT EVEN optimizing
Something you really need to ingrain is that there is no virtue in having hyperoptimized code if you don't have an actual product to show for it
Everything (where there are many instances of an object being dynamically created/destroyed) should use object pooling in general, there's no reason not to
But no, you could easily get by that without
how do i make this function run whenever the values of a specific AnimationCurve or an int changes
plan is to get this to run in the editor btw
Do you need physics in your game? I mistake I see from beginners is them using Unity’s physics engine when making a game that doesn’t need it
its not an excuse for not doing it, but at this precise moment im in a bit of a rush, since a group of friends an i wanted to make a only-friend gamejam
I mean why not just.... do it. Who cares if you need it?
At this point you've spent more time considering it than it takes to code
Then don't 🤷♂️
is object pooling that simple?
Yes
it's literally just doing all your instantiation in one go instead of spreading it out
so i could learn it in under 10 min ?
yes
oh
Have you even looked it up?
Just go look up a guide. It is one script and some modifications anywhere you instantiate and destroy
i didnt know about object pool before hyunahri told me about it
Getting the method to run in the editor is another can of worms but you can run the function in the mutilator when it is set
Yeah, I meant since then and since you were told to look it up
It onlu takes a minute to look up
the WHAT
can u learn it in under 10 min? probably not.. can u understand it w/in 10 min sure..
Mutator. Typo
u were suggested using unity's builtin pooling stuff.. u should look into that
or u could go completely custom if u wanted
Oh just a headsup, a lot of versions are probably going to use delegates if you aren't familiar with those. If you don't want to learn that now, just use OnEnable and OnDisable and enable or disable objects when they enter/leave the pool
Unity had there own api for running things in the inspector but that is a whole can of worms
i didnt look the built in, i watched a video explaining it and he used scripts
maybe its the same tho
what is an ObjectPool type?
a class
so im basically making a reference to the class itself?
ObjectPool is anything u want it to be
oh true
then theres a static instance of it called instance
its like if i do: private MovementScript movementScript;
right?
like obviously not the same
more like if u did ```cs
public class MovementScript : Monobehaviour{
}```
so the static ObjectPool creates a class instead of a reference?
Don’t do this unless you’re setting up an array of pools
If you design it this way, you’ll only be able to have 1 pool because any new instance will wipe out the static reference to the last
i would like to make one for the towers, another for the skulls, for the mages (2 types) and for the bullets
Instead use a static dictionary of instances with the key as the gameobject name
ur only pooling bullets right?
These are not 2 interchangable things.
no im also spawning waves that are randomly generated
so if i need to pool more than 1 thing i need to make the static "ObjectPool" var or not?
https://blackcatgames.medium.com/easy-pooling-in-unity-6eef64ccf541
heres a simple artcle that explains it
Create a static collection
programmer humour at its finest
ty
And static methods for getting the needed pool or creating it if it’s not yet created
basically it'd be a static instance or Instance that u could call
to get ur particles /gameobjects when not being used
rcycled
poolManager is the object, instance is the class and despawnEnemy is the method?
No
PoolManager is the class, Instance is an object of PoolManager and DespawnEnemy is a method of the instance
ohhh
so the first one is the class, the second is the gameobject and the 3rd is a method
but what i dont get is what does method of the instance mean
i do not know what singletons are srry
no worries, a different thing, different use-case.. same underlying principle
The second one is an instance of that class.
so it basically creates a new instance of the class each time?
I feel like you need to go over some C# basics. Specifically, the Type system and the difference between types and instances/objects.
Hey guys. I am trying to play a crossfade animation when a new scene is loaded. I have a button that will wait a certain amount of time before loading a new scene, say 5 seconds. I also have an animation which is 3 seconds long. When the button is pressed, my game manager script should wait 2 seconds before starting the animation, and then continue to wait another 3 seconds before loading the next scene. I've tried to do this in code with two different Coroutines, the effect that I'm getting though is that the animation is not playing until after the scene has loaded. In other words its waiting 5 seconds. Here is my script as well as the crossfade animator controller:
https://gdl.space/oxofadakug.cs
yes i probably should, and most certainly will
It depends on the implementation, but usually no. Singleton pattern implies that there is one instance that you access via a static field reference.
this might help a little with the structure. https://hatebin.com/pngrmgbpaz
but as i said im currently in a bit of a rush, and even if i know that this is not the optimal way to procceed( which i know isnt) i would love to finish this game since everything left is the colliders/triggers and the ui
i do not know how to use abstract class
then go for it.. but if u run into any performance stuff u wanna change you'll know where to look
The abstract part isn't relevant, i just didn't want to code out the logic
the static vs instance is the point
i do not understand that code
ty for the code but my current level is like nearly non existent
Nothing external ever interacts with object pool instances, instead object pool instances only register themselves and handle actually creating and handing off their objects. Everything flows through the static methods, allowing for easy debugging
what is string doing here= static GameObject getObject(String objectName)
the pools are indexed by string, so to get the correct pool (which itself contains the correct object) we pass in the name of the object we're asking for
we use the name of the object to check in which pool it is?
Dictionaries map the first type to the second type, so in this case string -> pool
Start with debug logging all the relevant values to make sure they are what you expect.
so when we put in a string, it gives us a pool (hopefully)
If you changed string everywhere to just be GameObject you could instead pass the prefab itself, or if you wanted to use hashes or enums or whatever, it wouldn't matter as long as its 1 to 1
i also need to learn Dictionaries
practically name is probably the worst possible way to do this lol, but I figured it would be more legible that way
god damn im a newbie to this lol
i've confirmed that the levelLoadDelay is 5 and the length of the animation is 3
just think of dictionaries as a list of unique pairs
unique pairs?
That's not all the relevant values, though, is it?
In a dictionary, all keys are unique. Every key must map to one and only one value
ie, if a key "name" maps to "bob", it cannot possibly also map to "john"
however two keys can map to the same value. ie "age" and "wealth" can both be 50
im getting a bit confused over all these new things that i dont understand completely
The main advantage is that a dictionary is a good collection when you want to be ablet o access specific things very quickly, rather than iterate over an entire list
with the object pooling, the type of classes,dictionaries, etc, my mind is becoming a rollercoaster
im a bit slow if i may say it
so its a bit hard
because the key only maps to one value ?
tl;dr version. I have a lot of stuff and I want to act on all of it -> list. I have a lot of stuff, and I want to access specific ones individually -> Dictinoary
its because of how the memory is structured and its very technical
You only have 2 options then:
- learn correctly
- implement it using only whatever you understand 100%
just know that it's fast and it stays fast even at very large sizes
is it bad if i: do it as i know, and once my friends an i finish this mini game jam, learn it the correct way?
Take half an hour and just read up on the basic collections in C#, it will make EVERYTHING easier going forward
tons of issues can be completely sidestepped by using the right collection type
okay im going to take a look into that
Like you don't need to dig into big o notation and 'why' they work the way they work, just know which one to pull out in a pinch
There's no good or bad. There's no one to judge you for that aside from yourself.
In general, I'd say look at List<T>, HashSet<T> and Dictionary<TKey,TVal>. Later on you'll want to also learn Queue, Stack and LinkedList, but those can wait
Wdym by "harmful"? Is it gonna explode someone's head if they play a game with bad code? Probably not.
no
Are they gonna experience lag/ performance issues? Maybe. It depends
Are you gonna experience issues with extending on the project? Probably yes. Is it bad? It's up to you to decide.
Go and read up, then try to implement one collection of each type into your project and come back here to review
you'll learn alot more that way rather than overthinking it
i really dont have the time for that at this precise moment
Then I really don't get what that conversation is about
you've spent more time talking here than it would take to learn any of these things
If you don't have time to learn, do it the way you know.
It's like a bike, once you get it going a few times it'll become second nature
probably not, i dont know why but i suck at learning
Learning to use your tools saves you time, usually even in the relatively short term
the classic example being new programmers accidentally creating a bunch of duplicates in a list fo what are supposed to be unique objects
yes but i dont even know what hashSet is or what its used for
That's kind of the point isn't it?
This is kind of an excuse. Learning is difficult to anyone. Yet you need to go through it if you want to get better.
neither the <T>. what does t even mean?
now that you say it kinda
i feel like im acting childish for some reason
Have you tried searching it or asking chat gpt
Because you are, just look these things up and ask us to clarify
but im just currently under a lot of preasure because of time and circumstances (which is also sort of an excuse)
It's okay to have questions, but you need to actively help yourself instead of making excuses. Learning sucked for all of us
It's so annoying to see people say here "I just suck at coding/learning". Then freaking learn. There's no easy way. Everyone went through that. Don't deny their effort.
After some more debugging the crossfade.GetNextAnimatorClipInfo(0) will always be the Transition Idle state instead of the Crossfade Out state. Transition Idle obviously has a length of 0 so loadLevelDelay - the transition Idle state length = 5, hence why the animation is playing after the scene has loaded
It's a game, you're not going to sell it. No one outside of your friendgroup (and most in it) will not care about it at all after about 5 minutes. Learning to do things properly will let you create things that you're proud of and make the entire process easier. The better your foundation the easier it is to build on it
agreed, i want to say srry for my past behaviour
okay
fresh start
what should my plan be now
Sounds about right. One thing to note is that your transition doesn't even start at the point in time.
learn this?
I think you know List already, but just lookup hashset, if you want to skip dictionary for now that's fine
at a super simple level, hashset is just a collection where every item is unique
ie if you use a list and add 0 twice, you now have a list with two zeros in it
I say: if you're in the middle of a game jam and have to submit it soon, do it first. Even if it's weird and has bad code, it's fine. It's a valuable experience as well. After done with that, go through proper learning though.
ive seen people use that for randomwalk generation ç
if you do the same with a hashet, it has one zero no matter how many times you try to add more
what is ie
for example
I think lists and hashsets are the last of their issues. There are many more basic things that they need to learn first
That is a generic. The T is short for Type
You fill it in with the type you want to use when implementing it
For example, the class List uses generics so you can store any type
public class List<T>
MyType newList = List<MyType>
You’re already using them, dw about it
You’ll get to it later, it’s a weird concept
for what i know its: bool, int, float, etc etc etc
Those are types.
Also every class you make is a type
gameobject, and so on
Every class, struct, and enum are all types
i want to learn about class types( i dont know if its called like that)
public class Enemy : MonoBehaviour
Enemy is a type
Monobehavior is just a class
Is is a class, which you inherit from
It’s already defined in Unity, you’re just inheriting from it, it’s not part of c#
what am i inheriting from it?
MonoBehaviour inherits from Behaviour, which inherits from Unity.Object I think
That you should google. Lots of things though
Like .gameObject, .transform, .tag, etc
I wouldn’t worry about digging too deep on this, just learn how to use it
btw, ty for even if i was a crybaby still helping me out and having patience, not only to you but to everyone here and everyone that has helped
i have a problem and its that i want to understand things at its most
That's what we are here for. To put you on the right path.
i dont like to use int for example, i like to know what an int means and then use it
Experience and use will do that more than trying to understand BEFORE using them
The worst thing you can do is try to learn every bit before trying to use it. Never do that
makes sense
All of that is covered in the documentation. It depends on some other knowledge though. That's why you need to go through a structured learning program.
seems like what im doing
Default int is
0000 0000 0000 0000 0000 0000 0000 0000
I mean, practice is important of course. But you can't grasp the whole thing without the theory
so an int cant be bigger than that number but with the zeros being 9 for example?
Agreed, I just mean that practical knowledge will put theoretical knowledge into a far more understandable perspective
No
i think you were the one that said to follow this path to me variables
data types
conditional statements
switch statements
collections (arrays, linked-lists, lists)
loops(for, while, do)
functions/methods
references
scope(global, local, parameter)
LINQ
sorting algorithms
inheritance
composition
classes
abstract classes
interfaces
polymorphism
SOLID
namespaces
events
exception handling
Debugging
break points
algebra
calculus
basic trigonometry
I think we're all confusing them. Speaking about concepts that are too early for them...
Not sure what you are asking here.
It is binary
oh
I don't remember. Maybe I did. It would be easier to just google "C# basics" and follow the first link that looks like it covers things from the very start.
i thought that you meant that when i declare an int( and dont assign any value) its value is "that amount of zeros" and not one 0, and the way int works is it changes the zero needed(or other number if already changed) to the number that we want, therefore having a limit of "that amount of zeros", but instead of a zero a 9
okay surely will
It is that many bits, all assigned to 0 as default
You’re mixing up value and the actual bits
It is a 32 bit value
yes i didnt think about it being bits
They meant that it's the default value of int in binary. Again, too early for you to pay attention to that now.
before anything,
will it have a big performance issue if i use( lets say 3000) rigidbodys and colliders?
Yeah sorry. You just said you don't know what an int is. I just wanted to point out that it is extremely simply just 32 0's until you assign a number
i know what an int is
No one knows
a whole number
Try and find out
If you use them all at the same type, probably pretty bad. But it depends on many factors.
How you use them is going to matter a lot more than the actual amount
well they will be flying across the screen
Yes, and how you decide where they fly and spawn is going to probably be the important part
like in this video
how would that perform?
How it would perform if I coded it is very different than if you do or anyone else, we all have different approaches and different system specs
I will guarantee you don’t need 3000 bullets though lol
Even tohou and the like doesn’t hit anywhere near that
if (Input.GetKey(KeyCode.LeftShift))
{
shiftHeld = true;
Debug.Log("ShiftDown");
if (shiftHeld == true)
{
if (speedAcceleration < 15)
{
speedAcceleration += 0.01f;
}
else if ((speedAcceleration > 15))
{
//nothing lol
}
}
if (Input.GetKeyUp(KeyCode.LeftShift))
{
shiftHeld = false;
Debug.Log("ShiftUp");
if (shiftHeld == false)
{
if (speedAcceleration > 1)
{
speedAcceleration -= 0.1f;
}
else if (speedAcceleration < 1)
{
//nothing lol
}
}
}```
So basically when I hold left shift DOWN it will send the message and increase acceleration
but when i put it up it doesnt send a debug message and doesnt accelerate
Before we even check the code, are you sure you’re using the right input system?
but im pretty sure im already around the 300 hundred or so
I think?
At 3000 in 2d either the bullets are so small as to be invisible or you can’t see the screen
okay
Your GetKeyUp is INSIDE the GetKey, so it can never be true
then my perception of reality is completely altered lol
OH
At that point, just make bigger individual bullets and fewer of them
Why do you think you need 3000
Then just go make the system, don’t use hypotheticals unless they relate to your actual requirements. This is just over optimizing lol
If you need a car to go 60mph, plan to make that car, not a Ferrari
as i said, a big problem that i have
i need to ignore my thoughts about it
Then just solve it
i overcomplicate systems that could be solved so much easier but i try to use weird equations
i try to
Made some progress on making the character walk/run using an animator, but I am still having an issue.
I don't know why, but when I try to run forward, it executes the Walk animation, even though the speed and position matches the criteria to execute the run animation. There are other animations that are not executing as intended, even when the numbers are matching in the inspector. Any ideas? Thank you very much!
for some reason the gliding isnt working correctly, it doesnt stop gliding and the jumps dont reset im pretty sure ```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Jumping : MonoBehaviour
{
private Rigidbody rb;
// to count down to five seconds
private float TimePassed = 0;
private bool CanJump = true;
private float JumpsRemaining = 2;
private float JumpCooldown = 5;
private bool Gliding = false;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{ // jumping
if (Input.GetKeyDown(KeyCode.Space) && CanJump)
{
Jump();
JumpsRemaining -= 1;
Debug.Log(JumpsRemaining);
Gliding = false;
if (JumpsRemaining <= 0)
{
CanJump = false;
Gliding = true;
Debug.Log("hello");
}
}
// making the cooldown
if (!CanJump)
{
TimePassed += Time.deltaTime;
if (TimePassed >= JumpCooldown)
{
CanJump = true;
JumpsRemaining = 2;
TimePassed = 0;
}
}
// starts gliding
if(Input.GetKey(KeyCode.Space) && Gliding == true){
rb.AddForce(Vector3.up * 10, ForceMode.Force);
Debug.Log("Im gliding");
}
}
void Jump()
{
rb.AddForce(Vector3.up * 5f, ForceMode.Impulse);
}
}```
Hiya! I'm making a character controller where the character is looking towards the golden vector, and I have the vector of movement working in the normal directions, but I want it to be relative to where the character is facing, how do I do this?
For example the green line would be like me pressing A and W but the character isn't facing that way.
My question is how to make it work based on where the character is facing
You can either calculate the movement vector by directly factoring in transform.forward and transform.right, or you just run your world-space vector through transform.TransformDirection()
Gliding is only set to false again when a jump occurs, and if you've started gliding then the cooldown prevents you from jumping. So you're effectively stuck in glide mode until the cooldown times out and you jump again
what do you suggest I do?
The first thing that comes to me is creating a new condition to drop out of glide mode in the case that the player is gliding and releases the space key
alright, thank you I appreciate you a lot
Took a while to understand but tysm
took a while to understand transform.TransformDirection
I probably should have elaborated further 😅. I'm glad you've sorted it out though. It's definitely a useful tool
omg got it working you saved me so much time ty
no dw at times like these its better to learn to research yourself
is there any better way to use
if(!Mathf.Approximately(movementJoystick.Direction.x, 0)){
animControl.SetBool("isMoving", true);
animControl.SetBool("isFlying", true);
} ```
to write
``` if direction.x is approx. 0 and direction.y is not approx. 0 then do #code ``` so its not spaghetti
im making a unity 3D game, My Character player looks in direction of cursor/mouse. It also has a gun in his right hand. So the problem is when the gun shoots, it doesnt shoot in the direction of the cursor because cursor is making the player look on it. I want such that the cursor gets binded to my gun's direction
{
mousePos = Mouse.current.position.ReadValue();
Ray ray = mainCam.ScreenPointToRay(mousePos);
if (Physics.Raycast(ray, out RaycastHit hitInfo))
{
Vector3 targetPoint = hitInfo.point;
Vector3 direction = (targetPoint - player.position).normalized;
direction.y = 0f;
if(direction != Vector3.zero && direction.magnitude > minDistance)
{
Quaternion targetRotation = Quaternion.LookRotation(direction);
player.rotation = Quaternion.Slerp(player.rotation, targetRotation, Time.deltaTime * 10f);
Cursor.position = Input.mousePosition;
}
}
}
assign the Mathf.Approximately checks for Direction.x and ``Direction.y` to bool variables, then use those variables in your if statement. easier to read . . .
idk if its unity or IDE, but it feels wrong
Instantiate is a static method from the Object class. if it derives from a unity Object you can access it, otherwise, access it from the Object type (class) itself . . .
Instantiate is a static method defined in the Object class, if you don't derive from it you have to call it like you do there.
the thing is, IDE says that i can call it without MonoBehaviour.
nvm, it says that its better to call it with Object.
That's pretty much generic suggestion when you access static member of base class
UnityEngine.Object.Instantiate doesn't look so good tho
So I have a working combat script but now I want to add spells to my combat.
Each spell has a unique effect.
When a spell is cast in combat, how do I find and execute it's effect?
My game will have 50-100+ spells, do I just huge a giant switch statement?
I guess I could also make a new class for each spell that extends Spell and just call Spell.Cast or something
But that seems like a ton of work, might be more future proof though?
There are many ways to organize it.
One way is composition. Have a set of minimal components of a spell and combine them in a sequence or graph. You could have several types of components, like a base(projectile/touch/ares), effect(damage, heal, whatever), modifiers(repeat over time, condition, etc).
Then creating new spells would be just a matter of combining all these components into a spell instance and only write new components if you really need something new that the existing components don't allow you to do).
wow that is very interesting! I will probably refactor my code into that at some point in the future, when I know more what I want the end result to be exactly
i have a script that loops and instantiates an Enemy gameobject instance. What would be the best way to keep track of enemy1, enemy2 and so forth? Aren't they all Enemy(Clone)?
when instantiated, you can store the enemy in a collection: array, list, etc . . .
if I place into a list or an array, wouldnt it be just Enemy(Clone) for all of the enemies
that is just the name of the instantiated GameObject. when instantiated in the scene, the GameObject will add " (Clone)" to their name . . .
what would be the best way to differentiate if not, name?
These structures don't change the reference of the item added to them
They all have different indexes in your array or list
differ how? enemy types? if so, you decide that. it could from an enum, class, tag, etc . . .
i think it could be as simple as what sashok said
i guess i would just make the list or the array public so other class can see it.
Guys i need help...
I did inventory system for items, and make them dropable and etc, but not i have no idea how to make items usable, they are currently ScriptableObject's with prefabs.
I want to make different prefab with script that will instantiate when player use item, is it good idea or there is any other way? i just dont have any other ideas.
or i could add method to interface and use same prefab and script, and just call different method in it
Add public abstract void Use()
to your item scriptable object, then add a new SO called UsableItem that inherits from your original Item SO, and then add
public override void Use(){
Debug.Log("Used item.")
}```
And, how do i add code in UsableItem SO? like, i want different items act different
I will have to make different SO for every item type?
using UnityEngine;
public abstract class UsableItem : Item{
public MonoBehaviour itemUseScript;
public override void Use(){
itemUseScript.enabled = true;
}
}
Something like this could work.
maybe ill stick to using prefab with interface..?
I dont think its good idea to have script to do smth.. isnt its same as spawning prefab?
"I don't think its good idea to have script to do something..."
w.h.a.t?
I dont understand what public MonoBehaviour itemUseScript will do, what its even for? am i creating object with this script or what?
You assigning script to add item use logic.
Hmm.. It means there is no diff with just having an Interface and script that will handle dropping object, using it and etc?
I'm not sure, I'm not that one ultra-smart game dev, that's just my implementation :clueless:
Adding an abstract method to the base class would require to make the class abstract too, and thus make it non-instantiable, and every class deriving from Item, non-usable too, would have to override Use
Same lol
You can test every way of implementing this and choose the best way for you
Okay, ill try.
Anyway, thanks for helping 👍
Ah-

I forgor
What exactly do you want to do when you "use" an item?
And how do you want to use an item
From inventory-level? While holding it?
Im gonna have a LOT of diff items, so, basicly, potions, keys, bombs, and etc, so, i wanted to make different class for each item and make Interface for them
Nah, player dont hold them, they are just in inventory, they are not stored as objects while they are in inventory
Thats what i made rn.
It does sound to me that an Interface (IUsable) is a better option here
I have "IItem" interface
The way I did it is just adding a flags field, activating a flag shows an array where you can add different behaviours
you can have more than one on an object
I know
What type of items? like, there is only few types or you make new flag every time?
so
public class Potion : IItem, IUsable, IDrinkable
public class Cake : IItem, IUsable, IEatable
etc, etc
One type of item, a few flags (usable, equipable, etc) and several modules for behaviour
Im also going to add weapons... i want to make separate inventory for them, like, there is gonna be a lot of guns and i want them to be stored separatly and not as items
How can I fix this? I have a vertical layout group, it works with messages that >1 line, but if it's more than 1 line... I'm getting this.
not a good plan, a Weapon IS an Item
Yeah, but its gonna be equipable in hands and player wont be able to use them like items
you are just overcomplicating things
I think text should have ContentSizeFilter, and layout object should have one too, but only for vertical
Welp.. i planed to make only 3 slots for items and 2 for weapons
Sit down with a piece of paper and pencil and draw out the items you want and the relationships (what they have in common) between them.
This will help you design your system correctly
It did fixed the problem, but now I can have only one line of text
Screenshot of text..?
Oh, wait-
It works
I just need a little bit more characters
Alright, it's works... but not
Try using minimum?
What "minimum"?
Change Vertifcal Fit mode
It made it better, but didn't fixed it
I have no idea, does other/small message size fit text or not?
Because that is what your code is doing
Hi guys
Can I ask something?
I have this model I made in blender and it comes with armature (bones) and I imported it to unity. After that I created a script that has addforce but somehow the model is not affected. I already added mesh collider(convex), rigidbody, and navmesh. Meanwhile Imported the model again but without the armatures and the addforce work on it. What might be the cause of it?
what
could you help me
what kind of help do you expect on the basis of 2 screenshots?
I want to display the high score of the player in the place of N/A
I know what you want, I asked how can anyone help you using the information you have supplied
!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.
could you say what kind of information you need
the lowest time taken by a player to complete the particular level should be the high score
#854851968446365696 tells you how to ask questions.
The first thing I see is you have made no attempt to debug this code. Do you even know if it is running?
Is there an alternative to the static keyword that still allows to be edited in the inspector but has the same effect of having the static variable be the same across every version of the script?
No. But sounds like you want a Singleton basically.
This
if (time == float.MaxValue) return "N/A"; // Handle uninitialized time
is obviously where the N/A is coming from. So debug time
heard of singletons before. same with factory's. Some kind of software design patterns
Ok thank you but how to do that
Debug.Log ? It should have been the very first statement you ever wrote in Unity/C#
yeah ok
Yeah, I'm using a script to keep track of all the items in the game. Currently I just have two lists, one being a static and one being not static and exposed to the inspector. and in the start the static list just becomes a copy of the non-static list. Which is prob a bad practice.
indeed it is. The Singleton pattern is definitely what you want
Thanks
hope you have a nice day
Hi all, Im using a few prefabs with just a sprite renderer and initiating them as "splatter" once a character jumped. It looks good, but can't help but notice the overall large amount of gameobjects sitting in the Hierarchy and wondering if it could potentially cause lag. Is there a better way to go about it?
if the gameobjects are not long lived then you could look into object pooling
hmm gotcha, object pooling is kinda like recycling unused game objects so I can reuse them quicker in the future right? For example let's say they don't go away, is there any method to kinda keep them permenantly there without it being an "gameobject" (seems like it would get intensive)
you are correct on your assesment of object pooling.
No, there is no way to have a gameobject without a gameobject.
You can mitigate the runtime impact of a gameobject by making it static, not sure if that applies to your use case
Don't overthink it
you can have thousands of gameobjects without any significant performance cost if most of them are disabled at any given point
If you're just trying to setup a script at the beginning of the game and need to grab everything in the scene, you can just use RuntimeInitializeOnLoad or a static constructor with one of the Object.Find methods
Nah, I mean like a database containing a list of all the items that can be obtained in the game.
at the current point, my items are scriptable objects. So I need to assign them somehow into the database.
Dump them all in a directory in Resources and Resources.LoadAll<your object type>
Although in general I'd also strongly caution against using scriptable objects that way, it's personal preference I'd suppose
Why would you caution against it?
SOs are, imo, a noob trap and kind of crap
They provide absolutely no benefit, are very easy to lose data with if you change the class, overcomplicate editing the data of individual instances and make it impossible to separate your data from your game
oh yes, and what alternative non gameobject related system do you advise?
What does using a scriptable object provide that you wouldn't get more easily by simply using a CSV file?
Storing data externally in CSV/JSON/XML/markdown of choice
great plan when you dont need references
That way non-programmers can also work on your data without needing the entire project, and it's easy to add modding support later'
If you need references to individual objects rather than the just the type itself then something has gone horribly wrong with the design
if you need string format data something has gone wrong with your design
That doesn't even make sense but go off
External data files allow you to have multiple contributors who don't need unity, easily share data files and edit together using any collaboration tool and with appropriate parsing logic can handle essentially any datatype. It also means that if you update Unity or have bad luck with the editor or need to rewrite your data structures you don't need to worry about references or data actually being lost.
rofl, there is no way I would ever allow anyone to edit raw data if I want to guarantee data integrity
You're completely missing the point
If you don't trust your team members, then you probably shouldn't have any
This is a lot easier to understand at a glance and balance/edit than having 14 separate scriptable objects sitting around a folder in unity
All you would do to make references in Unity is store these into a static dictionary when loaded and use a key that you can write in the inspector, I usually prefer strings but anything would work.
man, it takes an hour or so to write a custom editor AND you then have data validation to boot
Data validation just goes into the map class or your factory. I'm not sure what you mean by a custom editor
Pretty much any modern IDE already supports all markdown formats by default
and the actual IO is handled by CSVHelper or Json.NET or whatever you prefer
Scriptable Objects are great if you have a singleton and don't want to just use a static class for whatever reason, but using them for classes where there are many instances (like items in most games) almost guarantees that your project will grow massively in complexity as data is added, which is always something to avoid
Another trap ofc is people using them as 'item' and not 'item blueprint' lol
but that's just a structural thing
off-topic question here. Is it possible to initialize the length of the arrays inside a jagged array
like "private int[][] levels = new int[30][8];"
making it so that there's 30 arrays that have 8 elements in it?
no, but if you want to do that you wouldn't use a jagged array in the first place because it is not jagged
oh my bad, I just thought jagged array meant an array with arrays inside it
this is what I get for coding at midnight, pretty sure I'm looking for a 2D array.
indeed
We did something similar for the aurora engine. All strings and game-class data were stored in binary formats which were difficult for contributors to update/modify, so we converted it to JSON. Then when they submit the edited JSONs, our build pipeline validates the entries and if something is off we tell them "You made an oopsie".
To be fair though, it was kind of necessary because of how old the engine was. But I do see the use-case for this kind of design
but then you are using a data pre processor which is absolutely essencial because string format data is extremely easy to bork
Yeah, it has actually caused some major crashes because our pre-processor missed some problems early on in development
does not surprise me
Very difficult to consider ALL the possibilities strings can bork, it will undoubtedly fuck up somewhere
yep, which is why I would NEVER do it
We were in a corner and the alternative was an extremely high barrier to entry for writers on an engine that was extremely unintuitive to setup for our dev environment, so it was a necessary evil.
Meh, it's pretty straightforward to check if the incoming string parses to the correct type, particularly if you standardize your formats so you can disregard capitalization and trim all extra whitespace
It is so simple to knock up a GUI based custom editor, I cannot see why you would not do so
Because spreadsheets have been perfected over the past couple decades, so why reinvent the wheel
By all means, ship a custom editor with the project for endusers, that's a great idea
I'd definitely do that over having them go at the raw csv, but it's overkill for developer use and probably less efficient overall
It takes more time to produce a strong spreadsheet than it takes to generate a Win Forms program
in what world
And why would you use winforms anyway, just toss it at GPT4 and have it generate a webapp based on the CSV format, ime it pretty much nails it
in the world of someone who does both
And with that comment you have just lost what very little credibility you had, bye
Are you twelve?
Using GPT to generate csvs is so much riskier and prone to errors than writing a straightforward generator
100%
Personally I'd toss it together by hand since it takes about 10-20 minutes depending on how complex we're talking, but it's an option for someone not familiar with any languages besides C# and it's very straightforward to edit whatever code it spits out to fix up the output since really we're just talking about a set of rules for each output type + an end result string
I don't really see the point in having an editor aside from your IDE at all aside from maybe as a modding tool, but ymmv
fyi, a jagged array is an array of arrays where the inner arrays aren't all the same length. if they are all the same length, it's a matrix. both are 2d arrays, just different forms (and probably different internal representations)
Thanks!
Hope you have a nice day
Hi,
I write this program because I want to call the function of this class from an another override function. I see we can't use directly Coroutine in an override function. Can I optimised it or I have the obligation to do like this ? (I call ThrowArrow() in the other override function)
public void ThrowArrow()
{
StartCoroutine(DelayThrowArrow(2));
}
private IEnumerator DelayThrowArrow(float seconds)
{
Debug.Log("Arrow throws");
Vector3 position = SingletonManager.instance.playerObject.transform.position;
position.x += offsetX;
position.y += offsetY;
//Create the arrow in front of the player gameobject
//Quaternion.identity don't change the rotation of the object
_ = Instantiate(arrowPrefab, position, Quaternion.identity);
yield return new WaitForSeconds(seconds);
}
Why can't you use a coroutine in an override function?
When I write this, the IDE tell me that StartCoroutine doesn't exist in the current context
public class BowAttackBehavior : AttackBehavior
{
public override void Attack()
{
StartCoroutine(BowSystem.instance.DelayThrowArrow(2));
}
}
Is AttackBehavior inheriting from monobehavior?
No, it's an simple abstract class
Okay thanks
If you don't want to inherit from monobehavior, then instead you can create a singleton that you pass all your coroutines to
I thinked that Coroutine is from C# and not need to can interact with the engine
But now, I have this warning in Unity : ```
You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all
Because I have this : ```c#
private void SetAttackBehavior()
{
switch (attackType)
{
case weaponAttack.Bow:
attackBehavior = new BowAttackBehavior();
break;
case weaponAttack.Sword:
attackBehavior = new SwordAttackBehavior();
break;
case weaponAttack.MagicBook:
attackBehavior = new MagicBookAttackBehavior();
break;
case weaponAttack.Sarbacane:
attackBehavior = new SarbacaneAttackBehavior();
break;
case weaponAttack.Axe:
attackBehavior = new AxeAttackBehavior();
break;
}
}
monobehaviors need to exist on a gameobject, so you need to create them with AddComponent
Don't convert your class to a mono, just pass the coroutines to a singleton instead
Alternatively, are you sure you need coroutines? you could use async/await
async in #💻┃code-beginner, you're brave
Gotta start somewhere 😝
At this point he's going to have to make a lot of changes to implement coroutines
What is it ?
when he could save a lot of time learning async/await and use that instead if it's just simple delay/waiting
I don't really know of a good tutorial to point to for async/await... But microsoft docs aren't that bad
https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/
Fwiw this is my solution to the same problem https://hatebin.com/zfcdzbqnyv
A few lines of code to pass the IEnumerator and start the coroutine from a MonoBehaviour class?
Just seems messy to me if it's a self-contained class, but fair
hey, i have a question about the input system. i was thinking that it wouldnt be very good to keep creating a new instance of the input class in each script i need to use it so i just made one instance in my GameManager class and referenced it from there in a script, but im getting a object reference not set to an instance of an object error when i press start. did i do anything wrong? is this thing that i did with the GameManager even a good thing?
when you get that error it just means the code doesnt know what youre trying to reference is, how does the code know which object that script is attached to?
in my game manager class i have a static GameManager variable called instance which is assigned to the object itself in the start method, and the GameManager class is attached to an object in the scene. when im referencing the input class in my scripts im using GameManager.instance.input.
You should Initialize the singleton in awake not start
that is called a Singleton, fyi
And then you're likely referencing the singleton before it's been initialized
If you try to reference it in start/onwards when the singleton is initialized in awake, it should avoid those reference errors
i forgor about singletons, you guys are probably more equipped to answer his questions than i am
ohhh alright, i assigned it in awake and now it works properly
thanks for the help guys
I have this god awful way of handling turns but i cant really think of a way to handle the turns nor write this code better. any ideas?
https://pastebin.com/ffD9mh74
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
!code, use a paste site
📃 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.
Alright
looks like you need some arrays rather than individual variables
probably wiser to share my entire script instead
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
here we are
While I was testing my game yesterday, the fps started at 60 and dropped below. While testing my game today, my game, which normally starts at 60 fps, started with 2 fps. Thinking that the reason was due to the project, I opened my old projects and the same problem occurred there too. I wonder what's the problem? What causes this? If you look at the screenshot I sent, everything is on the ceiling in Profiler.
If it's every project, the problem is probably just your PC
check that you're not out of disk space
{
if(other.gameObject.tag == "Elevation")
{
rb.AddForce(transform.up * 5f, ForceMode.Impulse);
}
if (other.gameObject.tag == "Attractable")
{
hitCount++;
if (hitCount >= 3)
{
isAlive = false;
op.DeactivateGameObject(gameObject.tag, gameObject);
hitCount = 0;
}
}
}```
I have set this code such that if the object of tag "Attractable" is thrown to the zombie and it collides with it, zombie gets killed. Also I dont destroy the attractable/throwable item as Player can reuse it.
The problem is if the throwable item is lying on ground as it is, and if zombie walks and collides with it then it gets killed automatically. Please help!
can someone help mew ith the new input system , how can i check if the mouse button is Up like canceled ? checking if im pressing works fine , its just the mouse button up idk how to check for that, tried to make bools _isLeft/RightMouseButtonCanceled and then turning it false and true in the respective methods so im not sure what to do
Well, you'll need to provide some more details. Select a profiler frame and share the hierarchy view data sorted by CPU time, and ideally expanded a bit.
You should probably handle dealing damage from the thrown item instead. And then, what's stopping you from turning off the damaging behavior if the item falls on the ground / already hits something?
how do i stop the damaging behaviour? Also if i want to reuse that item i would want it to damage enemies again
Turn off the collider? Add a boolean?
There are a few ways
oh
you can have an isActive variable, or if this is on a separate component, simply disable the component (on the throwable). set it active or enable the component only when the player throws it. what happens when it hits the ground? if you want to reuse it, you'll have to set isActive to false or disable the component . . .
bool m_canDamage = true;
...
if (hit && m_canDamage)
{
// Damage whatever you hit
m_canDamage = false;
}```
got it
thanks
anyone know how to do this?
is there a good way to remap values? ideally with curves i can controll outside the script? i have a value that goes from -2.5 to 0 and for the ui i would need it to go to something like 2 to 1
AnimationCurve's
https://docs.unity3d.com/ScriptReference/AnimationCurve.html
im currently on that page but i still havent quite figured out how to implement
InverseLerp value using -2,5 and 0. Lerp the result using 2 and 1
They're serializable and editable in the inspector. All you need to do in code is sample(Evaluate) it.
Hello guys. Maybe someone can recommend tutorial on Youtube about doing inventory like in Minecraft?
ok, so im guessing on the curve the x achsis value is what i get out and the y axis value is what gets transformed?
okay fixed it , used isPressed() for the mouse button down and it works perfectly and for the mouse button up i just used WasRleasedThisFrame()
X axis is the time of the curve. The value that you input. And the Y is the returned value.
ok, so if i want to transform -2.5 to 2, i need to put it and -2.5x and 2 y?
Yes. Though if you just need to map 1 value, I don't see a point of using a curve.
its a time value that fluctuates between -2.5 and 0
KISS!
floar t = Mathf.InverseLerp(-2.5f, 0f, value);
float newVal = Mathf.Lerp(2f,1f,t);
thx
They mentioned they want it to be controlled by a curve and outside of the script though.
I suspect that was somewhat of a red herring
Even so, they can evaluate the curve and pass in t . . .
making a system where the cinemachine camera shakes when the player starts running
right now it works by broadcasting an event when the player starts running and one when the player stops running to display the screenshake
but i'm struggling to get it working well with other features like jumping which i just added
are events the right way to go about this
How would jumping be related?
I could be misunderstanding what you're trying to do, but this seems very overengineered for a simple first person camera
the camera shake is kind of an illusion to the footsteps
so when you jump the camera doesn't shake as much
😭 maybe
but it's interesting
So, simplest solution, is there any reason why your camera shake (headbob?) can't just check if you're grounded or not?
public class CameraShake : MonoBehaviour
{
[SerializeField]
private CinemachineBasicMultiChannelPerlin perlin;
private Coroutine _currentCoroutine;
private void Awake() {
perlin = GetComponent<CinemachineBasicMultiChannelPerlin>();
}
private void HandleSprintChanged(bool isSprinting) {
if (_currentCoroutine != null) {
StopCoroutine(_currentCoroutine);
}
float targetAmplitude = isSprinting ? runAmplitude : walkAmplitude;
float targetFrequency = isSprinting ? runFrequency : walkFrequency;
_currentCoroutine = StartCoroutine(LerpPerlinValues(targetAmplitude, targetFrequency));
}
private void HandleJumpChanged(bool isJumping) {
if (_currentCoroutine != null) {
StopCoroutine(_currentCoroutine);
}
float targetAmplitude = isJumping ? walkAmplitude : runAmplitude;
float targetFrequency = isJumping ? walkFrequency : runFrequency;
_currentCoroutine = StartCoroutine(LerpPerlinValues(targetAmplitude, targetFrequency));
}
private IEnumerator LerpPerlinValues(float targetAmplitude, float targetFrequency) {
float startAmplitude = perlin.AmplitudeGain;
float startFrequency = perlin.FrequencyGain;
float elapsedTime = 0f;
while (elapsedTime < transitionDuration) {
perlin.AmplitudeGain = Mathf.Lerp(startAmplitude, targetAmplitude, elapsedTime / transitionDuration);
perlin.FrequencyGain = Mathf.Lerp(startFrequency, targetFrequency, elapsedTime / transitionDuration);
elapsedTime += Time.deltaTime;
yield return null;
}
perlin.AmplitudeGain = targetAmplitude;
perlin.FrequencyGain = targetFrequency;
}
}
would it make sense to have a public bool of if my character is grounded or not
also how do i check for that
usually it's a raycast from the rigibody to the floor in an update frame but that sounds like a performance cost
raycasts are practically free
and you're going to need it for a lot of different things in all likelihood, so yes I'd make it public and if you want to cover all your bases just set it up as a property that shoots on an on change event
Also, totally up to your personal taste, but in general you don't use perlin noise for this, you use a sine curve to emulate how the head naturally moves
how do you implement that
i'm currently just working with what cinemachine provided
the preset handheld shake noise
Is there a specific reason you're using cinemachine? Or is it just a learning project
probably skill issues lol
i'm new to unity
Don't use cinemachine to start with
Learn to do things with the basic camera first, cinemachine is its own entire ecosystem
Nothing wrong with it, but you're basically diving straight into the deep end, and you really do not need it for a first person view
alr ty!
https://hatebin.com/tqnrnfrvik Here's a very simple headbob script, just replace playermovement with yours
Take a shot at figuring out how to do the grounded check and ask if you have any questions
currently i had put the ground check in a collsion check
but i can just toss it in update?
private void OnCollisionEnter(Collision other)
{
if (IsGrounded())
{
OnJumpChanged?.Invoke(true);
}
}
public bool IsGrounded()
{
return (Physics.Raycast(transform.position, Vector3.down, _rayLength));
}
ty this code looks way more sane and readable
Use a public IsGrounded bool and just update it each frame in update
Use raycasts instead of collisions
Try to use a layermask too, check the docs if you haven't tried that before
Bump x2
that headbob script in use and the hierarchy I use for fps cameras in case thats helpful
You just need to turn on "control child size" on the parent for size fitter to work, and shouldn’t have size fitter on child
Anyhow this doesn’t look like code problem
Thank ya!
is Application.wantsToQuit a good way to save data to the server before the player exits the game?
Depends
For example you don’t have good quitting events on mobile platforms