#archived-code-general
1 messages · Page 397 of 1
I would remove "readyToJump" in this method as this method should all be about OnSlope().
Comparison between two vector3 float usually isn't a good idea. You probably want to compare by angle instead?
I mean that you should give it some threshold to be considered slope or not.
Currently it only works if the ground is perfectly pointing up.
What if the ground is at a 1 degree angle? You dont want to consider that a slope
Your bool would then be slope < 0.5f or something.
Well, slope should just be renamed dot here
Where’s fogsight?
while it can be considered DI I don't think it's a particularly helpful example
// non-DI
public class MyClass {
public void Foo() {
MySingleton.Bar();
}
}
// DI
public class MyClass {
readonly MySingleton _mySingleton;
public MyClass(MySingleton mySingleton) {
_mySingleton = mySingleton;
}
public void Foo() {
_mySingleton.Bar();
}
}
here you have a few advantages:
- easily swappable implementations, especially when using interfaces
- not dependent on static context
- object dependencies are fully provided by the time it's build, so you have a clearer initialization step
but i have a maxslopeangle float and have set it to 40, i can move on the slope but as i said, i slide down and cant jump on it
why is that a useful post in a code channel?
Oh my bad. Wrong channel
Wrong server
Just go away, don't post anywhere about it.
This is not dependency injection, unless I'm thinking DI wrong here? Dependency injection involve requiring specific baseclass injection into the class component, that will use those components. This remove the need of .GetComponent<T> methods, and rely on service availability provided to the class constructor.
on earth i think
In software engineering, dependency injection is a programming technique in which an object or function receives other objects or functions that it requires, as opposed to creating them internally.
It's a very broad concept.
I think that's what I said? 🤔
that's describing the way the IoC container works, not DI itself
you're describing a very specific implementation of DI
I think you describe DI in a very broad terms of programming, but not very specific to unity in this case.
zenject, vcontainer etc are IoC frameworks that are one way of implementing DI in your code
There are certainly unity-specific DI techniques
(most programming models do not have a Transform hierarchy...)
I would argue that serialized references are already an excellent form of dependency injection
My components don't really know how they're getting these references
They just..show up
You need extra legwork if you need something between a singleton and a hand-assigned reference, I'd argue
I would say most people using DI frameworks in Unity are aiming for pure C# classes instead of relying on MonoBehaviours
for when some objects get one reference and some objects get another reference
yeah, the frameworks are the step between "delete all singletons" and "but that will make my code a horrible mess won't it?"
I mostly use pure C# classes but still haven't felt like I need another way of passing references around.
I'm trying to use OnMouseDown to do some simple buttons and it just won't work. I'm using it on tmp text with a 2D box collider. Anyone know why it might not be working?
I've done this so many times in other projects and I've tried all kinds of things troubleshooting it and I can't get it to work. So confusing
nope, I checkd that
I read it doesn't work if its a trigger so its off
Does that need the event system component?
But the former depends on Physics.queriesHitTriggers
No, this isn't UI
I have the event system compenent in my scene anyway
OnMouseDown is attached to MonoBehaviour
...but you could still be correct, actually
do you need a Physics2DRaycaster, perhaps?
thats for the Ipointer interface
that'd be the case if you needed an EventSystem
what would that component go on? I haven't ever needed to use that before
but I'm pretty sure that all of that is unrelated to the MonoBehaviour messages
Is there any other UI element over the UI Button? They could be blocking your raycast call.
I don't get any messages it just doesn't trigger
yup MB.OnMouseDown relies only on collider
nope, nothing layered at all
why not just use your own raycast so you know what you are actually pressing / hitinfo it
I wonder how it works under the hood
yeah I could try that out it just seems ridiculous to have to set up a raycast to do buttons
that or use the EventSystem
Doesn't Button expose event message? I'd try that first to see if you are actually getting event from the button script.
are you talking about UI button?
OnMouseDown doesn't work with UI
EnDespair did say button in their message. #archived-code-general message
if its a UI button the easiest IMO is using EventTrigger or Code / Ipointer interface
Oh yeah, I guess I could actually use the built in button. Not the same thing as OnMouseDown which is supposed to work for anything but since its not working this is probably the easiest
no its only for collider/physics
UI buttons are not physics
tmp text should not have collider
why not?
because UI doesnt need physics?
I put a collider on it so the on mouse down would work
is there a reason it wouldn't work?
OnMouseDown works for gameobject. Not UI elements.
becaue canvas is in screen space and physics dont calculate in that space
again. for UI you use EventTrigger or Ipointer interface
Oh, maybe that's my problem
I did a 2D project a while ago and I set up a button this way in my game design class
I guess it's not the same in a 3D project? idk
2D/3D doesnt matter you never put colliders on UI. Only if you want to make in the world interactions
like a player in world touching a physical button is different
(you place it on meshes /sprite renderer)
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/api/UnityEngine.EventSystems.html#interfaces
you can use one of these
or EventTrigger component if you want inspector
Hello, looking for a tip on how to handle stage data. The challenge at hand is difficulties, every stage has like 4 difficulty variations. The levels themselves are entire data driven, it's simply a list of enemy spawns and boss triggers.
In different difficulties sometimes enemies just have a single stat changed, sometimes more of spawn, sometimes new ones are inserted into the stage.
It seems like a major pain to change anything if you have 4 stage scriptabe objects for each difficulty and you need to play with some stat which is the same in all of them. How do "real" games solve this issue?
Thanks for any help!
SOs are great, why is that bad?
GameManager (Singleton) can be useful here to help achieve calling next stage, or fetch data to determine difficulties for your enemies to spawn in.
Maybe I explained poorly but I am looking for tips specifically on how to store stage data in a way that allows multiple difficulties and keeps as much between them in common as possible, while making it not too awful to modify in the inspector.
Loading or handling stages is no problem, I can figure it out, just how to store them.
store them in a POCO ?
POCO? Hold on let me google that
I mean yes that easy to do for a single simple stage, but I gotta add something else to make it easy to add more stuff to new difficulties on top of the easier ones.
Scriptable Object usually works best here. You can create layers of Scriptable Object to hold other definition of SO to define enemies difficulties. They can be interchangable from GameManager state.
thats very vague on what the actual problem is
SO + POCO
whats the issue?
okok I think I'll explain my current solution and I think it'll be more clear
XYProblem if you show your solution rather than explaining what the current issue is
still isn't clear what was wrong with SOs and why cant you "add to it" easy
sorry, my solution is really stupid so I thought it'd be better to explain problem first
For stats I currently store a list of numbers, so it basically just picks the one that corresponds to the difficulty (e.g. easy can be index 0, normal 1 etc.)
The entire stage data is mostly just a big list of spawn structs which hold which enemy to spawn, where, quantity etc.
My current solution is to make some enemy spawns be identifiable with strings, so you can references them in higher difficulties to be able to inject new waves before or after. This can also be used to replace any single enemy spawn.
The problem is that this method sucks because stages can have a hundred enemy spawns, which makes having four difficulties layered over each other a nightmare to remember. The strings are very tedious and slow to manage, especially if you want to go back and change stuff. Thankfully, I haven’t built many stages yet as I’m just prototyping this solution, which clearly isn’t very good.
So yeah was just wondering if there's a better way to insert / remove stuff from the spawn list while keeping all the stuff from previous difficulties.
Oh, this is a UI component on a Canvas?
yes
Yeah, the actual position of the object has nothing to do with where it gets drawn on the screen
what do you mean?
Go find the text object in your hierarchy and look at where it is in the scene view
assuming you're using an overlay canvas (the default), it should be very far away from the origin
(i was responding to someone else)
a bruh, sorry
yeah, I can see that. The x and y pos of the ui element represent it's distance from the anchor point
So OnMouseDown didn't work because the actual object was waaaaay off screen
an Overlay canvas gets drawn directly onto your screen after the rest of the scene renders
I thought of asking about that, but I forgor
on the flip side, using UI events will work properly
oh ok, that makes sense
you can add a component that implements IPointerClickHandler
if it's on the same object as something clickable (like a TextMeshProUGUI component), it'll have its OnPointerClick method called
I was just confused because I've done it this way before but maybe I was using a different type of canvas? idk. I've switched to using the built in buttons since this isn't even a final part of the game, its just for testing rn so I should be good now
so the list just contains spawns?
I'll definitely try this interface next time instead
Yes, you might have had a Screen Space - Camera canvas
well each spawn contains timing and stuff, and there are a couple other lists (like boss triggers), but they are so small its easy to just replace them in difficulty variations
This one gets physically positioned in front of the camera -- and it gets rendered along with the rest of the scene
Yeah that must have been it. Thanks for helping me figure that one out lol, I spent like an hour and a half yesterday trying to figure out why it wasn't working
(and then a World canvas just..sits in the world)
it's a lot like a Camera canvas, except that it doesn't get positioned automatically
Oh alright, and how do you want to add onto those spawns?
well basically you should be able to replace a spawn, add more or remove other ones. Like the amount of spawns doesn't neccessarily stay constant between difficulties
You as in the player or you the developer
me the dev
there's no stage editor or anything like that
what are the conditions you plan on using to adding onto this list
what do you mean?
You want to add / remove the spawns based on some conditions no?
my game isnt very complex so there's pretty much no conditions, only a list of time to wait and what to spawn
Perhaps you can give each spawn group some tags to identify its "meaning". Is it something that MUST happen every time, or is it okay if we threw it out and put some other enemies in?
That would let you run through your spawn list and make changes based on difficulty
well thats basically waht I have now but it makes modifying data, especially if you wanna go back and change stuff kind of slow and tedious
Should I use the unity's ObjectPool<T> or create my own with a dictionary and queue
I've had a good time with unity's pool classes
although I mostly use them for collections, not unity objects
Unity's works well enough, no reason not to use it unless you find it somehow doesn't work for your use case
I'm making a bullet pool system however different gun have different bullet for example the grenade launcher or the smg gun
okay, so you should have multiple pools!
Yeah
So I'm not sure how to do it
Cause if I wanted to use different pool I would need a different script for each gun
You can put the pools themselves in a dictionary keyed by the projectile type
No need for different scripts per gun
I personally just map an enum value to each projectile base type
Keyed by the projectile prefab, even!
I see
Should I make the pool T type gameobject though?
I am looking at some tutorial and they are teaching me to use the script class instead
It should be broad enough to cover anything that needs to fit in the pool
If every projectile has a Bullet component on it, then that's the appropriate type
But how does that work though
Cause the pool is the Bullet script
Not the bullet object?
I'm kinda confused at this part
I don't understand this statement
ObjectPool<Bullet>
Yeahh
This is an object pool that handles Bullet objects
Isn't the Bullet a script of the object?
But how does it get the gameobject from it though
When you instantiate an object that happens to be a component, Unity instantiates the entire game object
(and then you get a reference to the component on the newly-created game object)
[SerializeField] Bullet prefab;
public void Shoot() {
Bullet shot = Instantiate(prefab);
}
But what if I have the Bullet component that happens to be in multiple objects
Yeahh
You'd have a separate object pool for each one
You can do something like
Dictionary<Bullet, ObjectPool<Bullet>> poolMap;
You'd use Bullet prefabs to index the dictionary and get an ObjectPool<Bullet> back
Ideally, you'd use Interface for IBullet, which you can label GiantBullet or SmgBullet class?
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Pool.ObjectPool_1.html
The example they have may help you understand it. You write a method to create each object in the pool, which is called to initially populate each object.
Thank you for the clarification
Yep. You basically tell it:
- How do I make a brand-new object?
- What do I do when I fetch an object from the pool?
- What do I do when I return an object to the pool?
- What do I do if the pool is too big and I need to discard an object?
Good suggestion
At this point it might as well be called IProjectile. Bullet, Missile, Grenade. They have to spawn from a point, and does damage when impact.
I read that but it's still a little bit confusing
Thank god there's a good community
Now I know how it works
Action<T> is a method that takes a T and returns nothing, and Func<T> is a method that takes nothing and returns a T
in case you were unfamiliar with those
Wait whaa
I really didn't know
I just know that T type can be used inside a class where you don't predefine the type
that's generics as a concept
Right, that's the most common name you'll see for a type parameter
so I have a method with this signature:
public static bool TryMemoize<TArgs, TMemoized>(TArgs tuple, Func<TArgs, TMemoized> ctor, out TMemoized result)
It takes two arguments:
- A
TArgs - A function that takes a
TArgsand returns aTResult
And it gives you:
- A
TResult
It gives you an existing object if it has one for those arguments, and otherwise, it runs the function and gives you the result
Talks about Action<T> and Func<T> is a little bit advance for this subject here, as this would infer a umbrella term of shotgunning methods implementation for this. To answer the question above broadly, Use ObjectPools for specific class type that's commonly used in your game to help relief instantiation performance call.
Bullet would be a good example that needs to spawn immediately, and multiple of times per frame.
Particles and enemies would be another good example to use ObjectPool too.
"infer a umbrella term of shotgunning methods implementation" is a confusing phrase
well, "umbrella term" would mean something that covers a lot of ideas
Shotgunning method means you can feed in any kind of custom method you created into the argument, as long as it meets the requirement of either Action<T> or Func<T>.
I typically avoid this as it makes troubleshooting a bit hard to follow. It's almost like callback in other programming language.
Dang the more you know I suppose. I didn't even know that had a name
I have never heard that term before
the closest I've seen is something like "shotgun debugging", which is when you just...throw random crap at the wall and see if anything sticks
I'd just call that higher order programming -- you get to treat functions as values!
Learn it from working experience in the industry. 🤷♂️
"shotgun method" does not appear to be a meaningful term beyond people talking about this concept
Yep never heard of it either apart from the debugging term
I'm still in university 🤓
The point of the delegate is that you can feed any method that conforms to its signature, that's what they're made for after all :)
I love delegates
I found out that I do not need to manually use a dictionary to create the objectpool
There's something called DictionaryPool
Hopefully it works
No, that's something unrelated
a DictionaryPool is used to pool dictionary objects
I haven't used that much, but I do use ListPool pretty often
Ooo
How is that different from the normal list?
So you get the list from the pool
instead of creating one?
It lets you re-use lists
Owhh
that way, you aren't allocating a new list and then causing reallocations as you fill it up
Ohh so when reallocation is needed it will get from the pool instead of creating a new one?
No, the list is completely normal
The point is that you can re-use a list instead of creating an entirely new one
That's it. The pool does nothing else.
Oh I see
Howdy folks! I'm currently trying to rework references between objects in my game, but I'm not sure how to best do it. My current plan is to have the manager object which spawns all of the objects related to the character (such as the health bar and such) reference those after instantiating them as well as giving them a reference to itself, so that all of the scripts relating to my character can access the other objects when necessary. Is there some better way to organize this and/or to give references to the various objects, or does this seem good? Here is a rough diagram of how things interact at the moment:
I did something similar and created a "PlayerSetup" script that initialises all of the different components
It can be simplified with the singleton pattern and the observer pattern
I don't think the singleton pattern can work since this is a multiplayer game, though I could be wrong
public class PlayerSetup : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
if (GetComponent<NetworkBehaviour>().IsOwner)
{
// Assign this player to the camera
var camera = Camera.main.GetComponent<CameraFollow>();
camera.target = transform;
camera.Init();
// Assign other components...
}
}
}
local multiplayer?
or online?
Both
I mean some things can certainly still be a singleton - e.g. the "character manager"
I think the netcode for game objects is abstracted enough that local and online is the same process right? Not unless you're talking splitscreen
How would that work? Do you mean just the code for spawning the parts?
Yes, it is effectively split screen
Also, in case it wasn't clear, the character manager script is part of the character, and makes it so that once the network manager (or my local multiplayer character spawning script) creates the character, then the character manager spawns all of the parts directly owned by that character
I mean… static List<Character> PlayerCharacters { get; set; }
Oh true, I could also look at making a list like that but with a custom class that holds the characters, health bar, spellbook, etc. as references
And so as long as I give each object a reference to their character's instance of the class (or even just the class's index in that list), they could use that to reference the other objects
I try not to create a manager for stuff like that, the way I look at it is like...
Assign Prefab to network manager
Player Joins
Gameobject created across all clients
Player setup assigns just their players game object with all the stuff they need at the client level
Counterpoint - make a prefab that has all of those things in it with references to each other predefined.
When they spawn, you can write a little code to have them all decouple from each other (if that's even needed)
I like that idea a lot, but without having a single class that has references to everything whenever I need to reference a different part of the character (e.g. if a protection spell changed the color of the health bar), I can directly access without having to add an additional reference through the inspector. Would that not quickly turn into spaghetti with needing to have a lot of those objects have references to each other rather than each of them referencing one class?
Is there a way for non-MonoBehavior classes to subscribe to Unity events such as Update and LateUpdate? I don't mind subscribing to a C# event from inside the class.
Make a MonoBehaviour that fires events and subscribe your non-monos to them
public class MyDriver : MonoBehaviour {
public static event Action OnUpdate;
void Update() {
OnUpdate?.Invoke();
}
}```
You could also import the ECS library and create a class deriving from SystemBase:
https://docs.unity3d.com/Packages/com.unity.entities@1.3/manual/systems-systembase.html
I wonder if you could avoid MB by modifying the playerloop
But then you're dabbling into ECS which is a whole new world...
If you could hook an event there somewhere
Definitely can add a new event to the player loop, but it's a lot more complicated than writing a MB IMO
And so I have to have a separate game object in the scene with the component?
yes
Or is there a way to have this MonoBehavior classes in all the scenes?
make it a DDOL singleton and put it in a bootstrap scene
Or use [RuntimeInitializeOnLoad] to create a GameObject and AddComponent to add this script to the object, then make that object DDOL
As I understand, it will load this automatically when the game initialized.
Thanks a lot, PraetorBlue, I'll look into this tomorrow, I'm out of time for today
The reason I want to do this, is so I can have my actions updated:
[UsedImplicitly]
public class Action : MonoBehaviour {
public delegate void ActionEvent();
public event ActionEvent Began;
public event ActionEvent Ended;
public bool JustBegun { get; set; }
public bool JustEnded { get; set; }
bool UpdateWasCalled;
public void Begin() {
JustBegun = true;
Began?.Invoke();
}
public void End() {
JustEnded = true;
Ended?.Invoke();
}
public void Update() {
UpdateWasCalled = true;
}
[UsedImplicitly]
public void LateUpdate() {
if (!UpdateWasCalled) return;
UpdateWasCalled = false;
JustBegun = false;
JustEnded = false;
}
}
And the reason I have this on my Character and not using the built-in InputAction by Unity is because I can't set InputAction from code.
And so I won't be able to control the character from an AI controller and not a player controller.
And right now it's a MonoBehavior, so I create a whole component on the character for each action it can take.
We can modify the main loop?
This looks very interesting for what I'd like to have: the default C# events for all the default events: Awake, Start, Update, etc.
Hi! So I had a question regarding player jitter/stutter. So I recently ran into an issue of the player jittering and stuttering when messing around with Fishnet. I thought that this might have been simply a networking issue. But after reverting my player movement script essentially back to singeplayer/local, the jitter remained. When putting the scene and game view side by side, I can actually see that occasionally the player is the one jittering and occasionally it is the cinemachine camera that is jittering. I tried making it so that the camera does not move and the player character does jitter even with a stationary camera. But then I tested in a build with the camera following the player and there are screen tears. Overall just very confused as there seems to be conflicting signs that it is the player jittering or the camera jitting, was just wondering if someone had seen this issue before.
Might be both a camera issue and a character movement issue
How is your character moving?
If rigidbody, is interpolation enabled?
So my player moves through velocity setting. The weird part is that I didn't have interpolation on in my player rigidbody2D when it was perfectly smooth. I have tried turning it on and it does not really help.
iirc update method should probably be Smart update or fixedUpdate
The info box might be related to the issue
I suppose this is related to the networking?
Or why is the physics set to run manually
yo Osmal
cinemachine brain's update method was originally on fixed update but i saw online that some people were running into issues with cinemachine and that putting it on late update helped, in my case it did not xd
oh and it was still jitter? This might be a networking issue then
normally physics dont run on clients but are kinematic and simulated by server
havent used Fishnet though
tbh im not sure im going to take a look rn, as before i pretty much had interpolation off during the entire project as i didn't have any jitter issues
yep so i just found that one of the components in fishnet has a default component that turns the physics mode to scripting 💀 tysm this was such a headache i added that component and then made some changes to some player movement code so i thought it was related to the code i wrote TOT
its silky smooth again
Cinemachien should be on Smart Update
Rigidbody interpolation should be on
And lastly - the trickiest part - you can't be doing anything that will break the RB interpolation
ah yeah that'll do it for sure
bump
Is there anything wrong with adding additional components to the object that impacts their behaviour? That way you're not referencing the class, but instead applying effects to object. (Almost reminds me of DOTS/Tagging system)
I don't get what you mean
For example, if you add posion to Player1, you can add "Posion" component to player1 that impacts the player's movement and decrease health over deltatime, until posion wears off. You can reset the timer if Player1 get posion again, or add additional modifier stack to the existing component. The component would be responsible to reference required "target" component when added to the game object, but you don't have to worry about referencing other gameobject when it should only affect the direct game object it's attached to.
The spell itself should not change the healthbar color. That's not the spells's job!
Whatever draws the character's healthbar should be able to ask what effects are currently applied to the character and color itself accordingly
DOTS tag system is similar, where it queue all object that is tagged, say "Posioned", and it runs through update stack to apply damage or movement.
yeah -- in the Entity-Component-System approach, you write systems that operate on entities with the right set of components
if you have both "Health" and "Poisoned", you get damaged regularly
Health bar would need to have their own "state" to display "Hey I've been posioned" with a green bar, or "Hey, I got immunity" and display fancy mario rainbow color UI overlay.
ideally, a status effect spell does very little on its own
it just says "hey, X, you have Y now"
It doesn't matter if I get a protection effect from a spell, from a potion, from an ability, or from somewhere else
Gotcha, that makes a lot of sense. At the moment I already have it so that effects that change movement speed and such attach themselves to the player.
Yeah, that makes sense. My main concern though is not for this example specifically, but just that directly setting every reference is going to make it feel like a tangled mess. I haven't used this sort of structuring in an environment with complex interactions though, so maybe if I follow good programming practices and keep everything modular it won't be a problem.
That's why you need to keep your concerns separated!
This is a very good thing to be thinking about -- the total amount of "things" that have to be able to interact with each other
What do you mean by "concerns"?
basically, what each of your classes's jobs are
Oh gotcha, that's true
If everyone has to do everything themselves, then your spell suddenly has to know how to:
- change the color of your health bar
- affect how much damage you take from a fireball
- insert itself into the correct part of the status UI that lists your status effects
suddenly this spell is deeply intertwined with your entire UI
Yesterday I had to go through some godawful code from when I first started and made the health bar, and for some reason the health bar had to reference the player to get the health value, and the player had to reference the health bar to tell it to update in the first place
circular dependencies aren't the end of the world, but you can often avoid them
Yeah, just in general my whole script there was awfully written there
Right, so I assume I should make it so that the spell pretty much only needs a reference to the player (or whatever it's targeting)?
Yeah -- and all it would do is call ApplyStatusEffect
It's tempting to try to turn your entire game into effects and combinations of effects, but that often winds up being a pain in the ass
(like making damage itself an effect)
it gets silly very quickly
Makes sense.
But in this case, you could totally have a StatusSpell that just contains a list of status effects to inflict
So I assume I should get rid the of idea of a class that has references to each gameobject then, correct?
that'd be like a phonebook, I suppose
a big directory of every single thing anything might want to talk to
Yes, exactly, that was what my plan for how I'd give out references was
which sounds like it'd encourage bad behavior!
for example: suppose an enemy doesn't have a healthbar
we wouldn't want to try to find one when applying the status effect
Originally I had it all crammed into an irrelevant "CharacterInfo" scriptable object, and that got all of its references using FingGameObjectsWithTag, which as you can imagine was pretty awful
aeugh
yeah
I didn't really know how to code in c# at all when I started this, let alone how to structure things well, so I've got a few spots where there is some of the worst code you can imagine
you might want to take the opportunity to go and refactor that code if it truly is that awful. the process of refactoring will also help internalize how to do it better next time you might need to
I have been, that's sort of how I realized that I needed some major structural changes so that I would actually be able to split up scripts into smaller parts without them becoming a headache
is there a get around where you can have a canvas, context size fitter AND change the position of the Rect-Transform? I am making hotbar for my inventory
this is a #📲┃ui-ux problem -- but I can't see why there'd be a problem! ContentSizeFitter just resizes your RectTransform based on how much space it wants
Does anyone know of any good and bad practices to for making a database for an RPG like items, classes or enemies?
I like the way RPG Maker does it but don't know how to properly impliment the system.
I could make a Json, lists of Scriptable Objects or SQL from what I read. But each has a different implementation and can be annoying to rewrite if things don't work out.
SQL is for cloud databases, so don’t do that. JSONs and scriptable object largely depends on preference.
Well I plan to make a custom UI for this without editing the stats directly.
not necessarily for cloud only..
SQL is just a language, you can use any database that supports SQL for local storage too
SQLite is a common databse usecase for portable localstorage of organized data sets
idk if apple still does it, remember iPods? SQLite Database baby!
that being the case for OP s database is probably not needed.. Most games locally a database is probably overkill
what do you want to use the database for?
most likely JSON would probably be more than sufficient
An RPG. I just like the feel of the one RPG Maker has and I want to implement it into my project so I can more easily make stuff.
is it for saving stuff to disk? for querying at runtime? for multiplayer persistence?
so you don't even know why you need a database, tells me you don#t actually need one
I do know why. But when making functions I need to store the data somewhere.
databases are traditionally used for storing and retrieving things on disk in a performant way.
this usecase has mostly vanished and been replaced by concerns like structuring data and data consistency under async write access
modern databases mostly solve availability, speed and size issues
Yes that's more like it. I need to access the stats in a quick and easy way.
you don't need to store anything on disk or in a database while your app is running, unless you want to continue where you left of next time you start the app
Not when running. When I'm in battle, chances are I loaded all the stats already and don't need to change.
what you need for that is a save system (commonly implemented as a json serializer and object restore mechanism based on that json), a database is not needed for that
but you can use a database for that purpose, typically an embedded one like SQLite or more unity-specific things.
If this is database from rpg maker you're referring to. This looks like the equivalent would be scriptable objects in unity.
And yes a save system
In a way it is depending on what version.
i think what you call a database is basically "a game's systems"
Like I can see how the categories would go and how SQL and Json would help.
In a way. this is just what RPG Maker calls it.
RPG maker is VERY different from unity
unity is much more generic
you can re-build RPG maker with unity, but it isnt RPG maker out of the box
nothing close to it
Oh yeah I absolutely know. I dropped RPG Maker years ago to work on Unity. I just like the format but prefer the freedom Unity has.
if you want something like RPG maker you can look at assets in the asset-store that give you genre specific game-frameworks
none of those are particularly recommendable
I'm very well aware of RPG Maker Unite. But it still has limitations.
If you want to create something similar it would be a combination of scriptable objects (for "fixed" data like item stats and descriptions etc) and player prefs or JSON (for save state)
So like character stats being SO and saves being Json? I was thinking possibly Json for the stats and another for the save, but that could work too.
If the data doesn’t change scriptable objects should work fine
The reason why SO are recommended for that kind of data is because you get type safety, allows references to prefabs and such, and a nice inspector in-editor. If you want to be able to edit the data outside of unity, using JSON would be much easier.
For making saves its up to whether you want use JSON or not. A lot of the time save data can be generalized to ints and floats, so playerprefs are more than enough for this. You could even just use plain text. Either way to make save data you need to write to and read from a file.
please don't use PlayerPrefs for save data. it is not really meant for that and just bloats the user's registry
There are changes, but even then they would be temporary.
I know full well that it's not good for games of decent scale.
The main draw of Scriptable Objects is that you can create assets with them.
I prefer to use them for definitions -- not for runtime data
I have definitions that describe different kinds of emotions in my game
The actual values each entity has for those emotions are stored in a dictionary on the entity
it's not good for games of any scale. the only thing you should really ever use playerprefs for is storing preferences for the player aka the application. save data should not be stored in playerprefs because you end up bloating the user's windows registry with useless data that they may not know how to get rid of (yes, on windows playerprefs are stored in the registry). you are much better off writing any save data to a file on the disk instead
yeah, the "player" in "PlayerPrefs" refers to the built game
it's the Player, rather than the Editor
PlayerPrefs also good for storing data like cookies or sessionsIDs
not for long term storage like savefile
So a bad example I'm guessing would be to boot up the game and load the character's equipment onto the SO.
I don't see a reason to do that -- you could just as easily have stored that data in an ordinary class
To answer the actual question. The way I usually see SO or JSON (any data files) is the have a generic class that fills itself in using data thats given to it. Like having a list of item data (health potion, speed potion, etc), end then pass that data in some sort of builder:
itemObj.Build(itemData)
And have different generic classes for each type of thing that's different enough to make generalizing behavior not reasonable (items vs weapons vs armor vs enemies)
i had a long rambling discussion on this recently
I guess so. Was thinking going between screens.
Alright, I see. I do derive classes and use interfaces when making this stuff. Though it seems I might be going for lists of Scriptable objects.
Potential issue (or benefit I guess if you are testing and tweaking values after build) is that players can edit json easily
if the data is stored on the user's device someone will find a way to modify it, so worrying that json just happens to be easy to modify is kind of pointless
Players can edit anything on their device
I don’t think it’s pointless at all
Json is like very simple and not uncommonly known
I don’t think 99.9999% of players is gonna be editing scriptable object data
You will just annoy people like me, who will then spend several hours reverse-engineering your format out of spite
scriptable objects are not appropriate for storing save data (or anything else)
you can't modify assets in the built game
oh, you're talking about a database of game data, not necessarily saves
I thought we were talking about things like item stats
Right.
Ye ye
I would still not think at all about this. I would focus on what's actually good for the game developer
In that regard I think sos and json are like equally as good so for me things like this are the decider
If a person wants to cheat at a singleplayer game, then...go nuts
in that case it's likely all going to be assets anyway, so then json is perfectly fine because presumably it will be bundled inside of the unity binaries and not just stored right on the user's disk as plaintext since it will be created at edit time
It is
Ah fair I’m not really familiar with how building works
I guess a TextAsset would at least be compressed
If that is the case I don’t really see any benefit to json
Performs roughly the same job without being able to incorporate potential data transformations and with a more ‘cluttered’ interface if that makes sense to edit stuff
json could be nice because you can build some nice editor windows for (de)serialization to easily modify it then save it back to file
I don't care much about anticheat. I just want to figure out which format I'll be going with and making an editor UI to make things so much easier to put together.
That's one big advantage!
also, consider modding support
random example: Brigador is super nice to modify. The entire game is pretty much just JSON
Don't really need modding support for an RPG.
i think the point was that its that flexible to allow that easily
the most basic modding modify values in a keyvalue pair system
But ye I'm going to do it in SOs it seems.
Then SO will give you the editor ui out of the box. Can use JSON for save data that's accessed with a static class or something, and make some editor tooling to change it in editor so you're not making changes in a text editor.
I am running into some very large spikes in frame generation time in my standalone build. in the frame in question, is it doing some things I am not familiar with. anyone have any suggestions on how to get this to not take 2.4 seconds?
I'm trying to make an object pool here but I got this error
So what I'm trying to do here is just to make it pass in the gameobject into the createbullet so that I do not need to create multiple function for different bullet
Derp I read that backward. Remove (explodingBullet)
it expects a Func<GameObject>, you are passing it the return result of your CreateBullet method (which is just a GameObject)
How do I achieve that then?
remove the parameter for that CreateBullet method (unless you have need of calling that method elsewhere) and just use the prefab reference directly in the method
Do I need to manually make a function for createexploding bullet and createnormalbullet or smth?
Func<T> gets called in the ObjectPool, which gives you the gameobject it creates.
or you can just slap () => on the beginning of the argument
this would create an anonymous method that does what you want
You were probably thinking of Action<T> which takes in an argument, but this function expects Func<T> which returns you a value.
I have 3 different bullets though
then use this solution: #archived-code-general message
Ah shitt
even if the method expected an Action, that would still be incorrect
It wasn't meant as an answer, boxfriend.
i never said it was. i was simply pointing out that even if that was what they thought they were doing, it would still have been wrong.
How does that work though?
it creates an anonymous method using a lambda expression. it will be a Func that returns the result of the expression which would be the GameObject that the method call returns
Under the hood, it creates anonymous method implementation for the scoped behaviour. You can read more info here - https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-expressions
So the lambda function would act like a sort of intermediary between the action<t> and the function?
well the lambda expression would be the Func<GameObject> you need
it just calls that CreateBullet method with the parameter you supplied and returns the object returned by that method
I see
Thanks for the info
Thank you too
That helps
This looks GPU is struggling with it's work. Either your scene is super heavy, super heavy shader or something else is using the GPU at the same time.
If you have an integrated GPU it might be the one being used and not the dedicated one as well.
another option you have that would be a bit more verbose, but probably make more sense to you (but does almost the same thing) would be to just create other methods that call that method and return its return value. like
private GameObject CreateExplodingBullet() => CreateBullet(explodingBullet);
private GameObject CreateSomeOtherBullet() => CreateBullet(someOtherBullet);
then you would use CreateExplodingBullet or CreateSomeOtherBullet as the Func<GameObject> you pass to the object pool
well, that's super-confusing because this is just on a scene that shows my main menu. and i am running a 3080 😦
it's for sure more verbose doing it this way since you have explicitly created these extra methods in the class, but it might be a bit easier for you to wrap your head around. and would also be easier to change later on if you wanted to add extra functionality to those methods
Use the GPU profiling module to see what it's doing.
Using a dedicated GPU profiling tool, like PIX, could also be helpful
well it works now so I'm not touching it anymore
unless it breaks again
😅
can someone tell me if there is an issue with my code? the bullet seems to teleport on the first "frame" and idk what it's from..
{
Vector3 center = transform.position;
Bullet bullet = Instantiate(bulletPrefab, bulletContainer);
bullet.transform.position = transform.position;
bullet.transform.up = inputManager.lookInput;
bullet.transform.Translate(Vector2.up * .5f);
bullet.transform.RotateAround(center, Vector3.forward, degrees);
bullet.bulletInfo = bulletInfo;
bullet.velocity = (bullet.transform.up * bulletInfo.velocity) + (player.characterController.velocity);
bullet.gameObject.SetActive(true);
bullet.EnableTrail();
}```
this is to shoot a bullet in the direction i'm aiming with the anolog stick.
you set its position then immediately translate it half a meter upwards
if that isn't what you meant when you say it seems to teleport then be more specific
yeah but the game object is disabled? i should't see it right?
all of this happens before it is rendered. can you be more specific about what you are seeing or provide a video
i want to set the transforposition to instatiate in the Translate spot .5 meter up
i can't provide a video.
the trail renderer is creaing a line between these two points.. and i don;t want them to.
bullet.transform.position = transform.position;
bullet.transform.Translate(Vector2.up * .5f);
i want the bullet to start in that "half a meter upwards" position. how to do that?
it already is in that half meter upwards position by the time you call EnableTrail. so show that method since it's clearly where you are setting up the trail renderer.
the trail is already set up but just turned off.
{
trailRenderer.gameObject.SetActive(true);
}```
so i'm just enabling it..
i'll take two screnshots 1 sec
is it actually disabled in the prefab though?
yes
then consider just spawning the object half a meter up instead of setting its position then translating it. you can specify a position in the Instantiate method
yeah so this is what i want to do.
so do it then?
idk how to?
which part of that are you unsure how to do
how am i suppoed to get that position without using a transform? in other words, how do i find that point when nothing is there to reference it?
you have a transform though, it's literally this component's transform
Instantiate has an overload to set the position and rotation of the created object. that is preferred to use over setting it manually after creation . . .
exactly, why i'm translating it from there.
you should take a look at the documentation for the Transform component. you might find some useful methods that would help you accomplish what you want
without needing to call Translate on the instantiated object
why are you using Translate and assigning the velocity in the same frame? these will overwrite each other . . .
you're thinking of MovePosition
becasue i'm new to working with this and idk where to start, i'm just figuring it out and reaching out
they're translating the transform, then setting the velocity of presumably a rigidbody
have you looked at the docs for Transform yet?
see this is the kind of information i'm looking for. thank you. i had no idea, just talking to a brick wall over there lmao
no, that is not relevant
okay, in the future, i'd checkout #💻┃code-beginner then. some level of basic unity methods and know-how is expected here and will cause initial confusion (like now) since you're just starting . . .
everytime i post there no one answers me
not everytime.. i didn't earlier
are you moving the bullet by manipulating the transform or using physics?
whichever one you choose, it must remain the same . . .
the Translate call was because they don't know how to specify a position half a unit upwards in local space. there is no conflict of translate and velocity happening since the translate happens exactly once to get it to the correct position
they need to look at the docs to find the convenient method that will convert a point from local space to world space so they can get that position that is half a unit up in local space to pass to the Instantiate method
of course it seems like they've started to completely ignore me because other people have jumped in with irrelevant info so 🤷♂️
since they assign the bullet position, they can just use that position and add the code used in Translate to move it . . .
Translate works in local space by default so it's not just as easy as doing transform.position + (Vector2.up * 0.5f) to get their desired position which is why i've asked them to consult the docs for a helpful method
facts. i keep forgetting it's Space.Self by default . . .
i am using a rigidbody.
so no nothing is working... even though i pressed undo back to an untouched method...
hey guys! i have two questions and im not sure where to post the second one buuut!
the first question is how can i learn c# for unity development? is it better for me to learn c# overall then study the docs or...? but tutorials would be highly appreciated!
second question that i dont know where to put is that me and my girlfriend are getting into game development, whats the best way to transfer my changes over to her and vice versa? shes going to be on the level design part of things and im going to be on the programming side of things, tutorials and tips are also heavily appreciated!
Question 1: check out the pinned messages in #💻┃code-beginner. you want to start/go there if you're new and learning
Question 2: use Git for version control. you can download GUI apps to make the process easier . . .
What is the best method to outline an object?
I see online that there's the shader method or smth
Like I want it to outline the object when mouse is on it and the object is interactable
@zenith acorn are you using URP?
One way I could see you do this is by having having a separate layer for the objects you want to outline, let's call it "highlighted" or whatever.
You would uncheck that layer in your URP assets, add a render object (experimental) feature to which you would provide a fullscreen graph shader for the outline. Don't forget to only check the "highlighted" layer in the render objects feature.
As for the code something as simple as that should help you get the object :
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour
{
Ray ray;
RaycastHit hit;
void FixedUpdate()
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out hit))
{
Debug.Log(hit.collider.name);
}
}
}
Now instead of debugging the object you would simply change it's layer to "hightlighted"
And you need your object to have a collider, any collider
Then you should try the method I mentionned, it would be much cleaner for you only to set the gameobject layer rather than assigning it a material from script
Okie thanks I will check it out
If you have any question don't hesitate
There is also a renderfeature (hope ita still there) to swap materials on depth check in urp automatically
Okie I'll do it later cause I'm in class and I do not have my laptop with me 😭😭
Ooo
Yes you can do the depth check with higher, less or equal if I recall correctly
Looks like you have a good control scheme setup per bindings now. Sorry, I thought the forum post would have worked. You could try asking on that forum post or you could try that $15 asset store thing.
Hi in this coroutine im updating a value in a time.
TotalDuration is how long the coroutine should run, total exp is how much i have to get. But if i have, lets say, totalExp = 10, with this i only get around 6... where is the flaw? its the event raising?
The isUpdating value is a static variable to prevent concurrent updating from different objects
IEnumerator ConsumeItemCoroutine() {
float quantityCount = 0f;
while (quantityCount < 1) {
while (isUpdating) {
yield return null;
}
isUpdating = true;
durationLeft -= Time.deltaTime;
float quantityGiven = Time.deltaTime / totalDuration * totalExp;
UpdateExpEvent(quantityGiven);
quantityCount += Time.deltaTime / durationLeft;
isUpdating = false;
yield return null;
}
ConsumeItem();
}
mmh maybe duration left is useless in this, i have to use total duration instead, in the quantity count increaser
That would not actually prevent other instances of the coroutine from running and modifying the class variables. Coroutines do not run concurrently so no other code is running between those bool flips. So one instance will run, by the time it yields the bool is false, so the next instance can run to the yield, and the bool is false again, rinse and repeat
the problem was this. i didnt double check
since i can have multiple of these coroutine running, all of them are updating a value (and i show it in UI as a filling bar). There is no need to worry about that?
If multiple instances of the coroutine are running on the same object then they would modify the same fields so you should worry about that. If you prevent multiple instances from being started on the same object then it won't be a problem as long as the fields they modify aren't static (unless they are meant to be modified by multiple objects)
And none of that would run concurrently, coroutines are not multithreaded
ok so i have gameobject instantiated at runtime, each having a script that fire this coroutine
Yeah it's not a good idea to update a variable in a couroutine or an async function if it can be modified in the main thread anyway
Those would be separate as they run on separate instances of the component
Coroutines are not on a separate thread
Then concurrency is not a problem, just keep in mind that this variable should not be updated in thr main thread
I was talking about async functions
why? unity isnt multithreaded anyway if you dont force it
i mean doesnt everything runs on a single thread?
It does but you will have a hard time with immediate checks in a couroutine if you yield
Then where, pray tell, do you think this variable is being modified if not on the main thread and you understand that coroutines are on the main thread
by the way with multiple instances of the script running the coroutine i dont need to worry about the final result of the value i am updating , cause every coroutine are not concurrent. And even if at a given point i would add to the value i am updating they still will update the correct value at that moment
did i understand that correctly?
Yeah, my bad
Yes and no. In regards to your own code: yes, it will all run on the main thread unless you explicitly schedule it to run on a separate thread. But there is stuff in unity that will run on separate threads (lots of stuff is using burst/jobs under the hood)
ok, then my use case should be fine. Also im updating the value by raising an event through an event bus. thats also not concurrent right?
Provided you are not modifying static variables, then each instance of the component has its own separate values for the variables
No, unless your event bus is explicitly scheduling the events to be raised on another thread (and why would it, that seems rather pointless)
yes the structure is this
A Manager holding the info of the value (lets say saveData.exp) that subscribe one of its methods to the event bus.
the instances of the script that run the coroutine that raise the event of the manager with the value to add
thank you anyway
Hi! I am using AssetPreview.GetAssetPreview to get icons for my prop prefabs in my level editor. Every time I open my project, the asset previews are white the first time I enter playmode and gets the previews. This only happens the first time I enter playmode, and after that it works normally. Is there a way to fix this? And will they be white when I build the game?
Pretty sure AssetPreview is Editor only so wont even be available in a build
Oh well... That's unfortunate. I guess I'll have to create my own then. Thank you
I have a mystery!
I have, for whatever reason, learned to do
System.Enum.GetName(typeof(MyEnum),myEnum)
to get the string of an enum
However, myEnum.ToString() works perfectly!
Can anyone help me figure out why I learned to overcomplicate like this? I could have sworn that back when I learned this (a while ago) there was no better way. Or was there?
Was I just being stupid all this time?
I have a feeling you have confused this with the GetNames method which will return a string array of all the enum names
Ohhhhhhh you might be right!
I think I even remember the thing I was working on, when I learned it
So I'm following this tutorial down below, but it seems that it only works with shaded smooth object
Hey Guys! Welcome back to another CG Smoothie Video! In this video I'm bringing you guys a new Unity Game engine tutorial! This time, we're learning how to use the unity game engine to make 3d outlines around characters and objects in your game using the Unity Shader Graph! I think this is one of the BEST Outline tutorials out there! If you guys...
and when I try with object that are not shaded smooth
This happens
Ah from what I sew, and correct me if I'm wrong your shader inflates the vertices to give an effect of fake outlines, yes?
like if I add this to a capsule it works fine
I think so?
I'm not actually sure about that
Wait I'll find you a better shader hold on
Okiee
Until now, it's been tricky to make your own post processing effects in URP. It's going to become much easier in Unity 2022 through the new Fullscreen Shader Graph, and in this tutorial video, I'm going to create an outline post process to see how it all works!
✨ Snapshot Shaders Pro Sale: https://itch.io/s/89921/snapshot-shaders-sa...
This one should be good, the only downside if I recall correctly is that you can't change the size of the outline, if that's a problem let me know
Okay if you have any question, don't hesitate again
ohh
well can I change the color though?
Yes
this is not an outline shader, its an edge detection shader
True but for his purpose wouldn't that fill the same functionality
idk, i would think its not that great to generate an outline around a highlighted object for example, but idk what the OP needs ofc
"Like I want it to outline the object when mouse is on it and the object is interactable "
That's what he wants so you might be right
the unfortunate situation in U6, i think, is that there just isn't a good free outline shader/tutorial around
Did he say he was using Unity 6?
all good tutorials explain the principles of making a good one, but none of them translate to U6 without modifications and hand-coding all that stuff
no, but kinda the same down to URP 14, maybe even below
Haven't touched Unity 6 so I wouldn't know, is it that different?
U6 kinda requires you to use the render graph API which breaks a bunch of old free assets that don't use it and compatibility mode doesn't fix it (at least for the one's ive been using)
Seems very inconvenient. Is the render graph the new equivalent for shadergraph?
Lower level thing unrelated to visually authoring shaders https://docs.unity3d.com/Packages/com.unity.render-pipelines.core@17.0/manual/render-graph-fundamentals.html
Thanks I'll look it up
Someone from here knows about unit test? twt
here is a nice article about all the possible ways to make a nice outline: https://bgolus.medium.com/the-quest-for-very-wide-outlines-ba82ed442cd9
i don't know of any free implementation, that works, which doesn't use the (inefficient) gaussian blur method
So, can I check if webgl game was launched on mobile/anything havin sensors really, or not, without using a bit of javascript?
Hey, Im a beginner can someone lmk how easy or difficult would it be to develop multiplayer games?
what kind of multiplayer?
like a room with multiple players in that room and them doing some tasks that gains them points etc.
how competitive? for your friends only?
i have a team of 15 people. All of us are beginners. I want to know if i can get this done in 1.5 months with approx 1 hour dev/learning time each day.
@zenith acorn Anikki might have a better shader for your needs
zero chance
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives maybe this?
not a chance
ohh
it can be done, but its not often it does
why so?
it cant be done by 15 beginners
whaat is this even and how it relates
the 15 alone is a problem that makes it impossible
15 people not knowing what they are doing will result in incredible spaghetti code
you'll spend 90% of your time talking and fixing miscommunication issues
if you were doing 10 hours/day for 15 months you might just make something playable
if your unity game is able to run on mobile, I'm sure you could use a directive to check what hardware the code is being run on, and that makes a decision on how to run your code
I havent really used directives, never had the need. But thats my understanding of what theyre for at least
Thanks for the ping
-myEnum.ToString();
+nameof(myEnum);
nameof works at compile time so you can also use it in constants and attributes.
Enum.GetName doesn't make sense if you know the enum you grab the name from.
I'm testing it out
but the setting is different with mine
like mine looks like this
plenty of code ive seen has stuff like #if xbone #if playstation #if osx
and there's no pass index
lemme try it out
I don't think you can get it from within WebGL platofrm honestly
those are compiler directives not runtime ones
but I don't know the details
yeah that's more like it
motivation levels are a big thing, people who arent as passionate as the others wont put in as much work, as the director who's got the most motivation for this to be the dream game, but somebody whos only job is to program likely isnt going to feel so strongly to the project
this was written 4+ years ago and probably doesn't simply work, but the ideas are as valid now as then
Is there any tutorial for it?
Cause I'm new to this
🥲
obviously not
but it has all the code at the end
you just have to figure out how to implement it in your render pipeline
also team management is really tough, especially for people with little experience. Its a job in itself, and if management starts to fail the projects overall production can falter and it can be a death blow
Okiee thanks
make it 1 guy working 15 hours a day, honestly
having a huge team is kinda hard to work inside unity
like you need to sort out how you guys gonna split the tasks
and then the collaboration part like you need to push to github or smth
and all of you need to work at different scenes
OHh
and after you guys finish with your part someone need to combine them 💀
Ohh
there are version controls for unity, kinda...
but you need to pay for it though
project management is not a unity specific problem and version control wont fix it
15 beginners using git will just be a mess
I don't need very wide outline but just an outline like the picture
Will this method work?
you can also check out this one: https://github.com/Arvtesh/UnityFx.Outline
Screen-space outlines for Unity3d. Contribute to Arvtesh/UnityFx.Outline development by creating an account on GitHub.
this kinda works
so anyway sorry for bumping what is the most reasonabel way to decide if you enable mobile sensor controls or not
for WebGL
at least it does up to unity 2022 (URP 14)
I saw someone making a tiny plugin for that
Okiee thanks
which is... okay but it touches javascript
its good enough for 1-4 px outlines
sorry for the late reply, but yeah, now that you say it, it has to be because my movement script overrides my X velocity, as opposed to vertical, which is left to jumping and gravity
body.linearVelocity = new Vector2(Input.GetAxis("Horizontal") * HorizontalSpeed, body.linearVelocity.y);
Ive looked around for other ways to move the player, like body.addForce, that doesn't feel very responsive, which I don't think works well when I want to implement more precise platforming
maybe I could disable movement inputs to the left or right for a few frames whenever you collide with a bouncy surface that is to your side, but Im not sure how that would feel (it probably would have flaws too lol), but Ill try that out for now
In my game players create building objects and I've got them inheriting from a common Building class. I think it would be nice if the Building class had some static CreateNew() method so I could spawn in a new building, but obviously being abstract, I can't create a new Building. Is there a way of having the child classes all inherit a static CreateNew method which 'knows' what class they are, or is there a better way of going about things?
Main thing is I'd rather avoid having ten different Building sub-classes, each with identical CreateNew methods
Edit: actually, I could pass the type of building as an argument, which probably solves my issues?
AddForce can feel responsive if you implement it properly.
What I like to do is get the difference of the rb.velocity and desiredVelocity, then use that vector as a force vector, multiplied by some float number that vaguely represents acceleration
This way you only add the amount of force that is needed to reach desiredVelocity
And your character can still react to external forces if thats what you want
is desiredVelocity some kind of speed cap?
It's your target movement direction, in world space
In the simplest form, something like(moveInputX, 0, moveInputY)
Rotated with your camera/character if necessary ofc.
So it seems Application.isMobilePlatform works except it sometiems doesn't
iPad is the case
yeah quirky stuff
I'm a bit confused still, wouldn't that be 1 or -1, as in a multiplier to move left or right?
could you give me an example of how that is used?
I think he means an a speed cap
rb.AddForce(HorizontalSpeed)
}```
I asked if it was, and it wasnt
this was what they said it was when I asked about it
uh ohh I'm missing a faces now 🥲
Helloo I'm having an issue with my floating capsule movement where the capsule struggles to stay at a consistent height when moving on slopes. Any help would be appreciated! I'm confused as to why it's struggling because I'm dividing by fixedDeltaTime so it should literally be instant (the reason why I have a projectedDirection variable was because I tried to add the y on top of the target but that did pretty much nothing to help)
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.
Desired velocity is a vector. cs var desiredVelocity = new Vector3(moveX, 0, moveY); var force = desiredVelocity - rb.velocity; rb.AddForce(force * accelerationMultiplier)
I think I should specify, Im making a 2D game here
does that change much?
Same principle applies
are moveX and moveY preset caps or something?
for a specific direction that is
You can think of them as caps, sure
They form the velocity that you want to reach. Not much else to it.
so, I should make a switch/if statement, and if the player holds left, the moveX for moving left is used, and a different moveX if right is held?
i.e leftSpeedCap and rightSpeedCap or something
Hi, any idea why a moving sphere that collides with a cube in any angle results in the sphere moving along the face of the cube? I have no clue what might be causing this
what properties do they have?
- Any custom physics materials involved?
- Any code modifying their movement?
I need / want the spheres to not move slower than the lowerLimit, but can go faster but there would be a decay of speed back to the lowest limit, this is what I found on the net as a solution
You're reflecting the already reflected velocity
On collision enter happens after the collision has been processed
So your math here doesn't make much sense
You could either store the object's previous velocity (in FixedUpdate) and use that, or you can try use something like the relativeVelocity from the Collision to work it out
Also the code there is explicitly removing the y from the velocity
So that will definitely make it "flat" against the wall if the wall is a floor or ceiling
yes, I don't want the ballls to move in the Y axis, only on the floor, think of pinball or something like that
Ok
hi, is there a channel where i can legaly promote first episode of my new series on how to make a simple 2d game in unity?
after removing the inter collision logic to see if it works, and only keeping
if (_rigidbody.velocity.magnitude < MinimumSpeed) {
_rigidbody.velocity = _rigidbody.velocity.normalized * MinimumSpeed;
}
}
it still behaves weirdly
In what way?
Also you should probably try <= MinimumSpeed not <
thanks! just uploaded it there
it still glides along the walls instead of bouncing off of it
Oh
Didn't know that was the issue. Could you send a video?
Oh wait no nevermind I get it now
It's gonna glide off the ball because you're directly setting the velocity to the reflected one
So when it bounces of the wall it's just gonna come back
is there something set up wrong? ...
Wait no sorry again I need to follow along more
it should behave normally as you would expect it, but instead it doesn't bounce off, just goes along the wall
Could it be because you have bounce on the physic material set to 0?
I don't know if depenetration velocity is added onto the velocity people alter
I have removed that material as well to try it out
doesnt git have a like, maximum amount of GBs you can transfer per month though?
GitHub has data limts, yes
note that GitHub is not Git.
it's a very popular place to host Git repositories
There's no reason you have to use a remote repository. It just ensures that you don't lose your work if you throw your computer into the ocean
wait, i'm sorry, i still dont get it
so github as an app has data limits but git doesn't? and i was just using the wrong thing?
GitHub is not an "app"
GitHub is a website that hosts Git repositories for you.
They have limits on how much data you're allowed to upload
GitHub Desktop is an application. It provides a GUI (graphical user interface) for Git repositories on your computer.
I see, thank you for explaining me the difference, but does Git have a data limit?
no, beyond Git slowing down when you work with lots of huge files
and when i upload my changes, should i upload every folder (or pretty much just upload every single file in my computer) or should i just upload things i made and the scripts i changed?
you supposed to use Git LFS when working with big files (or non-text files)
then you can always pay for more bandwidth and storage in GitHub
You need to configure Git so that it ignores files that shouldn't be version-controlled
You should then version control everything that isn't ignored
LFS helps by moving very large files outside of Git's control, yeah
I don't use it in my games. I just shove everything into Git!
yeah, you can move it later on demand if the project gets big enough
i see, i'm sorry but i didn't get this part, so should i upload every file (not including the files that will be in the .gitignore) or just the ones i made or changed?
Hello, I have problem, I'm new to Unity and I started doing my own project without any help, my question is why "hitboxes" act weird - I mean I can see like 2 pixel apart here, I can't come exactly next to block cause of 2 pixels apart and I can't get between 2 squares
on the left is player and 2 next boxes to him on the right are walls, what do i need to change and can it be a problem in code?
and how can i update my game everytime she makes any changes and vice versa? i think thats with the unity version thing correct?
the files specified on .gitignore won't be versioned, that means you won't be able to send or retrieve them from your git repository, then you don't have to worry about mistakenly uploading them
otherwise you should upload everything
you either use Git or Unity Version Control, not both at the same time
if you're using git you just need to commit and push your changes to the repository, then she can pull the changes and vice versa
so its automatic? it will recognize the changes and update them? thats so nice!
which one should i use? git or unity version control? i assume version control, correct?
not really, you need to explicitly define what you want to include in a commit and then push it
Git is widely used in software development in general, but Unity Version Control should be more beginner friendly I guess
I would recommend just taking some time to learn the basics of Git and go with it
I never much liked the Version Control package
i had some really funny problems with it back when it was still called Plastic
I trust Git much more
using a graphical interface can make it much less intimidating (GitHub Desktop or something similar)
alright, thank you guys! ill take a look at git!
I'm using the unity's new input action however for some reason when I presses R there is error now
hey guys! another question is, will git work well with scenes? im seeing a lot of comments about it
of course, a scene is just an asset like any other
notably, most Unity assets are just YAML
Git will show you line-by-line changes to scene files (and prefabs, and many other kinds of assets)
read the full error message of the one above that.
Looks like you had an exception thrown inside your listener function
Are you using Visual Scripting?
Nope I'm not
I wrote an input manager that handles all the input
and the error that I get from is unity's script
So I have no idea where the error is coming from
😭
looks like it's coming from some visual scripting thing
Show how you hooked up your code to the input system
I didn't do any visual scripting though
I think you made a mistake there somewhere
right I think you accidentally did something with it
show it
And show how you hooked the input system up to it
I'm using this
using System.Runtime.CompilerServices;
using Unity.VisualScripting;
using UnityEngine.Experimental.GlobalIllumination;
get rid of these
probably just over-aggressive using-inclusion
thank you, VSCode, for dragging in a random Localization namespace
i didn't want my game to compile
Show the stack trace for this one too @zenith acorn
idk where this three come from
your IDE included them when you typed something
I swear to god like it wasn't there
How do I brighten a ui image through script?
change its color
ahhh I found the error
it seems that I changed the data type from a gameobject to a scriptable object instead
and I forgotten to change it there
thanks man
that'll do it
The question remains why the visual scripting system is involved at all here
I tried changing its color but it doesn't seem to be working:
In the start method I have these variables:
// Initialize the original color from the health bar's current color
brightenHealthBarOriginalColor = healthFrameImageComponent.color;
brightenHealthBarBrightenedColor = brightenHealthBarOriginalColor * 1.5f; // Brightens by 50%
private IEnumerator BrightenHealthBarEffect()
{
// Split the effect into brighten and revert phases
float halfDuration = damageEffectDuration / 2f;
float elapsed = 0f;
// Brighten the color
while (elapsed < halfDuration)
{
healthFrameImageComponent.color = Color.Lerp(brightenHealthBarOriginalColor, brightenHealthBarBrightenedColor, elapsed / halfDuration);
elapsed += Time.deltaTime;
yield return null;
}
healthFrameImageComponent.color = brightenHealthBarBrightenedColor;
elapsed = 0f;
// Revert to the original color
while (elapsed < halfDuration)
{
healthFrameImageComponent.color = Color.Lerp(brightenHealthBarBrightenedColor, brightenHealthBarOriginalColor, elapsed / halfDuration);
elapsed += Time.deltaTime;
yield return null;
}
healthFrameImageComponent.color = brightenHealthBarOriginalColor;
}
I guess it's an extension method?
That would make sense
I really have no idea
brightenHealthBarOriginalColor * 1.5f``` Isn't necessarily going to do much
it just got included randomly
ah, yes, that's exactly it
especially if they are already "full bright"
like I didn't even touch viusal scripting at all
the visual scripting package has a bunch of methods that work on any unity Object
(and then throw a runtime error if the type is wrong)
loll
When you tried to do GetComponent on a scriptable object, your IDE probably suggested bringing in the visual scripting namespace
which allows for these extension methods to be used
oh yeahh
I do have a getcomponent inside my script
An extension method lets you create new methods for existing types
maybe that's the reason
Also if you want to brighten a color, multiplying by 1.5 isn't the way. You'll want to convert it to Hue, Saturation, and Brightness values and increase the brightness.
Using these:
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Color.RGBToHSV.html
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Color.HSVToRGB.html
@raven basalt
And if the brightness is already 1, it won't do anything
should you script it or record an animation instead 👀
it sounds fine to me tbh
for example:
// Initialize the original color from the health bar's current color
brightenHealthBarOriginalColor = healthFrameImageComponent.color;
Color.RGBToHSV(brightenHealthBarOriginalColor, out h, out s, out v);
v *= 1.5f; // brighten by 50%
brightenHealthBarBrightenedColor = Color.HSVToRGB(h, s, v);```
@raven basalt
ok what I'm kinda confused rn
I have an enum type variable inside WeaponData
and by right I should by able to access it this way right?
I think the main problem with it is that it doesn't handle the bounds of the color space well. It works as long as rbg are each able to scale uniformly, but not if one of them hits the max value before the others
no
WeaponType is not inside WeaponData
it's on its own
You would just write WeaponType weapon;
Right, I was typing that out but it was getting way too long-winded :p
that's more succinct
I'm so used to using HDR colors at all times that it didn't even come to mind
why arent the serialised feilds for theese two game objects showing up?
showing up? or not showing up
if they aren't showing up, I suspect you have a compiler error elsewhere in your code - check your console for errors
Also just some code comments - classes should be "things" (like RaycastTarget or Raycaster or RaycastBlocker) not verbs, usually (like raycasting). Methods should be verbs.
Members (like cube1 and cube2 and hit) should be "things" or "descriptors" as well (cube1 and cube2 are great, but what's "hit"?) - and almost always not verbs. Probably something like raycastOrigin or raycastHitPoint or even raycast.
Naming your items well is gonna make debugging issues a lot easier later because your code should "read" like regular english.
and ray is underlined in red, so big RED flag
gotta pass in 'r' not 'ray' as you named your ray variable 'r'
i know i copied code that said Ray r and code that used Ray ray :D
very good reason not to copy/paste
raycasting is confusing in the documentation so i didnt want to type out a lot of code that wouldnt work
there is Ray, Racasthit, physics.raycast, and they all seem to do the same thing slightly differentl
The only one of thjose that "does" something is Raycast, because it's a method
Ray is a type
RaycastHit is a type
ok, but at which point in this process do you think your brain should be involved?
This seems like an "I don't know C# well" thing, not an "I don't know raycasting" thing
when it works
then i mess around with it to learn how it works
yeah i now realise ray makes the ray
phsycis.raycast detrects a collision
and raycasthit stores that collision
wrong, your brain should be involved even before you start coding
Ray is a datatype describing a ray
RaycastHit is a datatype describing how a raycast interacted with an object in the scene it hit.
why is physics.raycast and ray seperate?
why cant ray also have a method to see what colliders its merging with
also if physics.raycast takes an orientation and a direction isnt this the same as just making a new raycast? like for single use you dont also need to create a ray
i guess it makes your code more orginised
because you might use a Ray for purposes other than performing a raycast
a Ray is just a position and a direction
you can call Raycast with a position and a direction for cases where you don't already have a Ray
yeah i guess
i was under the assumption that Ray was a big package that did a lot more things than just holding 2 variables
it doesnt even contain max distance
Yes -- it's strictly a point and a direction
thats the thing about learning documentations
its hard to tell what is usefull and what isnt
especially when lots of things use the same name
Is anyone familiar with MessagePack for Unity? Why does my MessagePackWriter seem to not support writing strings with WriteString? Every example I've seen online allows this.
do you have an example handy?
https://github.com/MessagePack-CSharp/MessagePack-CSharp/issues/511#issuecomment-514104588
I think maybe this is a C# version issue - where some versions of C# automatically coerce a string into a ReadOnlySpan?
https://learn.microsoft.com/en-us/dotnet/api/system.string.op_implicit?view=net-9.0
I have zero understanding of how to read the version numbers for .NET
Maybe because that's ReadonlySpan<char> and this wants byte?
For now I'm doing writer.WriteString(Encoding.UTF8.GetBytes(key).AsSpan()); but it feels bad
Definitely feels something is off when WriteString doesn't accept string 😬
The second param of AddForce lets you apply force through different modes (https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Rigidbody.AddForce.html), essentially applying different math under-the-hood to make it feel more instant or progressive - alternatively if you need more precision, you could try setting and adding to the velocity directly (https://docs.unity3d.com/2023.2/Documentation/ScriptReference/Rigidbody-velocity.html - if your using Unity 6 then its LinearVelocity: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Rigidbody-linearVelocity.html), in this way youd likely be doing math with your game logic to determine how much and how often to add or remove from the velocity - you could use this approach in-part with raycasts as well if youd like, or even something like calculating the Vector.Angle or Vector.Dot product to figure out which direction to apply force if it shouldnt always be linear
For example, in my FPS game I have a vector to handle moving with input multiplied by some arbitrary "speed" (as you have now), and another vector I constantly drop to 0 over time to act as a "burst", then another fixed vector I use as a "buff/debuff" - so when my character should dash I increase the "burst" vector knowing itll "automatically" drop to 0 over time, when the player enters a trigger that should make them 2x faster I add to the "buff" vector, and if they take damage during this speed buff, I can drop that buff by a percentage (multiplying anything by a value between 0.0 and 1.0 gives you the percent of the value, so 50 percent of 200 is 200 * 0.5f), this means I can set velocity to movementVec + burstVec + buffVec, where each vec is doing math before setting velocity once at the end of the frame
why doesnt drawray take ray as an input, do i really have to manually put in a vector and position like in the unity example
do you not see it says 3 overloads?
Your "ray" also provides the first 2 params already
i dont know
the exmples just use position rotation color
so thought ray (position rotation) colour would work
I mean you can do ray.origin and ray.direction, you don't have to "manually" do it.
seems kinda funny that the thing named drawray cant take ray as an input directly and you need to split it
Sounds like my problem from above... #archived-code-general message
The biggest travesty is that DrawRay and Raycast have different shapes
different shapes? wdym
Different API shapes
oh right
Raycast accepts (origin, direction, distance)
DrawRay accepts (origin, <direction and distance in one>)
weird
im not too in depth on programming languges but couldnt they just make it accept one or the other?
physics.raycast also accepts the layermask but i dont need it to work
just make it both accept a ray and position rotation seperate
Yes they could.
they just.. haven't.
I'd imagine the Ray being a really simple struct is why they havent needed to
its just the inconsistency really
end of the day it is a debug function
Also it is not a huge deal, just give it aa origin and direction and you will be fine
On the bright side, there is a dedicated Physics engine visualizer window now that you don't have to write any code for at all.
I do agree the inconsistency is odd, they could easily just write an overload for DrawRay which accepts a Ray itself
Gizmos look like theyre the better choice for visualising a ray
Hi, I'm working with procedurally generated meshes for the first time and although I got the generation to work, it is very inefficient in triangle count. As of now, every single triangle is "1x1" and simply placed in a grid, however this results in 1,494,006 triangles even though most of the mesh is made up of flat parts. Is there a method to only merge/remove vertices in order to make larger triangles that cover more space and thus decreasing triangle count?
Code:
Fractal testFractal = new Fractal("ok");
//this simply returns a very large list of points and heights. I'm thinking something like if a vertice's height is the same as the last one don't add it?
List<float[]> fractalIterationSet = testFractal.equationSet(1000, 1000,levelOfDetail, 100);
Debug.Log(fractalIterationSet.Count);
xSize = (int)Mathf.Sqrt(fractalIterationSet.Count)-1;
zSize = (int)Mathf.Sqrt(fractalIterationSet.Count)-1;
vertices = new Vector3[fractalIterationSet.Count];
for (int i = 0; i < fractalIterationSet.Count;i++)
{
float[] spot = fractalIterationSet[i];
float height = spot[2] / 10;
Debug.Log(height);
vertices[i] = new Vector3(spot[0], height, spot[1]);
}
triangles = new int[xSize*zSize*6];
for (int vert = 0, tris = 0, z = 0; z < zSize;z++)
{
for (int x = 0; x < xSize; x++)
{
triangles[tris + 0] = vert;
triangles[tris + 2] = xSize + vert + 1;
triangles[tris + 1] = vert + 1;
triangles[tris + 3] = vert + 1;
triangles[tris + 5] = xSize + vert + 1;
triangles[tris + 4] = xSize + vert + 2;
vert++;
tris += 6;
}
vert++;
}```
If you need help deciphering my code, lmk :) (it's messy, i know)
or maybe some algorithm to merge triangles if that exists?
u can check height.. if triangles are at the same height u can assume they're flat and can make the smaller triangles into 1 big one
not sure bout the end goal. and what you'll need tho..
whats ur game-plan? other than just wanting less GEO which is what we all secretly want
also aren't there alot of tesselation resources out there that can do this type of thing?
bigger tris' where less detail is..
planar merging is the name for combining triangles that exist on the same flat plane
ahh thanky.. didn't know theres a name for it.. shoulda assumed tho 👍
Im poking around on github to see if anyone has implemented it
theres bound to be somebody who has
however Im starting to doubt whether the correct name for it is "planar merging", thats always what ive known it as, but not much seems to show up in general
Probably just "Mesh decimation" or "mesh optimization"
and specifically this is an optimization regarding coplanar triangles
https://github.com/Autodesk/revit-ifc/blob/e63d059c69489a7fab829bdef2f03ae09bb7d16c/Source/Revit.IFC.Export/Utility/TriangleMergeUtil.cs#L306 "merge" seems to also be used by people
yeah just ran into this
thought debug raycast wasnt working turns out it was so small the transform controls were covering it
how can i combine my raycast direction and length into one variable or "struct"
youll probably run into a sunk cost fallacy with trying to re-implement other peoples code when it comes to something like this, unless there happens to be some implementation that is designed to be used in a Unity project
what I mean is itd be quicker to write it manually than wrangling somebody elses code
never mind you just need to multiply it by a number
this seems like it would be suitable @karmic stratus
ya, thats what i meant by Tessellation ^
good stuff
hahah.. i tried to write my own plane generator.. and I suck lol
if my max values go above 256 it breaks...
reaaally specific and common number there 🤔
ohhh, its b/c im maxing out the 16 bits
i think
it might also be worth doing this in a ComputeShader, that could generate all the point data far quicker than the CPU ever could
Could it? There's a ton of random access going on when simplifying a mesh
I'd expect a GPU to struggle with that kind of thing
not simplifying, just running the initial code to create the points in the code from earlier
Ah, I see
was going to follow up about that before you replied to me 😅
absolutely would prefer that. i was just messing around
ill stick to my prefab plane until i can learn a bit more..
i always try to experiment w/ different things other ppl are doing..
like in ShaderGraph? i hope b/c i surely can't write shader code yet lol
doesnt unity have some sort of limit on the number of vertices its able to turn into a mesh?
im reading 65,535
shadergraph doesnt really have the ability to do anything like that
but compute shaders arent really that complicated, they seem scarier than they really are
with the default 16-bit index format
you can switch to 32-bit indices
i just read that 👍
im amazed i figured out the issue.. 100 worked fine.. 500 was broken.. i then got an idea to try 257.. broken.. but 256 worked fine..
🎯 gotcha
imma trust u.. 😄 i'll give them a look after lunch
i wanted to try something out for grass/shrubery anyway
It comes up pretty often!
now i'll be on the lookout, at first i was thinking it was the what i was using as collections <List>
16, 32, and 256 are about the only numbers that give me that reaction
I'm trying to write my logic for melee weapons in my game. Theres a variety of weapons, all of which have their own attack path. I don't want to do raycast where you simply see if something is in front of you, but rather have the weapon follow a path and see if anything collides as the path progresses. Does anyone know of a good place I can see this kind of logic in play? Having trouble finding anything on it
any tutorial, article, repository, helpful links to places in the engine that would help with this ^
Depends what you mean by "path"
generally games use a simplified cast or a couple casts for such things
it doesn't have to match the visuals perfectly.
https://www.youtube.com/watch?v=A3vCY-jU_tc i found a good resource like this a while back
EDIT: I now have a discord! Join to talk about various things and maybe even help me make my minibosses!
https://discord.gg/4eReG6w
TIMESTAMPS:
Slow-mo demonstration of hitboxes - 0:00
Daggers - 3:54
Straight swords - 4:27
Greatswords - 5:40
Ultra greatswords - 7:19
Curved swords - 9:08
Curved greatswords - 10:13
Thrusting swords - 11:06
Katan...
maybe worth just lookin at
I'm pretty much trying to copy Kingdom Come Deliverance if you've ever played that
oh yea, that darksouls video will be a good video just to see how they do their hitboxes.. i imagine it'll be pretty similar if u doing a medieval game/ sword slinger
not sure the complete details tho.. if i were to do a prototype of something like that i guess my enemies would have the rigidbody.. and the sword and melee weapons would be the trigger collider
and casting being another alternative like praetor said
