#archived-code-general

1 messages · Page 397 of 1

sudden inlet
#

so you mean i should change onslope from bool to float?

plucky karma
#

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?

hexed pecan
#

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

proud portal
#

Where’s fogsight?

eager tundra
#

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
sudden inlet
#

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

knotty sun
proud portal
hexed pecan
#

Wrong server

trim schooner
#

Just go away, don't post anywhere about it.

plucky karma
#

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.

vestal arch
heady iris
#

It's a very broad concept.

plucky karma
thick terrace
heady iris
#

you're describing a very specific implementation of DI

plucky karma
#

I think you describe DI in a very broad terms of programming, but not very specific to unity in this case.

thick terrace
#

zenject, vcontainer etc are IoC frameworks that are one way of implementing DI in your code

heady iris
#

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

eager tundra
#

I would say most people using DI frameworks in Unity are aiming for pure C# classes instead of relying on MonoBehaviours

heady iris
#

for when some objects get one reference and some objects get another reference

thick terrace
hexed pecan
#

I mostly use pure C# classes but still haven't felt like I need another way of passing references around.

jaunty sleet
#

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?

heady iris
#

Is it a trigger collider?

jaunty sleet
#

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

heady iris
#

oh, I see

#

it works on both triggers and non-triggers

hexed pecan
#

Does that need the event system component?

heady iris
#

But the former depends on Physics.queriesHitTriggers

heady iris
jaunty sleet
#

I have the event system compenent in my scene anyway

heady iris
#

OnMouseDown is attached to MonoBehaviour

#

...but you could still be correct, actually

#

do you need a Physics2DRaycaster, perhaps?

rigid island
#

thats for the Ipointer interface

heady iris
#

that'd be the case if you needed an EventSystem

jaunty sleet
#

what would that component go on? I haven't ever needed to use that before

heady iris
#

but I'm pretty sure that all of that is unrelated to the MonoBehaviour messages

plucky karma
jaunty sleet
#

I don't get any messages it just doesn't trigger

rigid island
#

yup MB.OnMouseDown relies only on collider

jaunty sleet
#

nope, nothing layered at all

rigid island
#

why not just use your own raycast so you know what you are actually pressing / hitinfo it

hexed pecan
#

I wonder how it works under the hood

heady iris
#

it's ancient

#

scary

jaunty sleet
#

yeah I could try that out it just seems ridiculous to have to set up a raycast to do buttons

rigid island
#

that or use the EventSystem

plucky karma
#

Doesn't Button expose event message? I'd try that first to see if you are actually getting event from the button script.

rigid island
#

OnMouseDown doesn't work with UI

plucky karma
rigid island
#

if its a UI button the easiest IMO is using EventTrigger or Code / Ipointer interface

jaunty sleet
#

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

rigid island
#

UI buttons are not physics

#

tmp text should not have collider

jaunty sleet
#

why not?

rigid island
#

because UI doesnt need physics?

jaunty sleet
#

I put a collider on it so the on mouse down would work

#

is there a reason it wouldn't work?

plucky karma
#

OnMouseDown works for gameobject. Not UI elements.

rigid island
#

becaue canvas is in screen space and physics dont calculate in that space

#

again. for UI you use EventTrigger or Ipointer interface

jaunty sleet
#

Oh, maybe that's my problem

rigid island
#

colliders = physics

#

UI shouldnt have physics lol

jaunty sleet
#

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

rigid island
#

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)

zealous lagoon
#

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!

rigid island
#

SOs are great, why is that bad?

plucky karma
zealous lagoon
#

Loading or handling stages is no problem, I can figure it out, just how to store them.

rigid island
#

store them in a POCO ?

zealous lagoon
rigid island
#

Plain Old Class Object

#

or CLR object

#

like a regular class/struct

zealous lagoon
#

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.

plucky karma
#

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.

rigid island
#

SO + POCO

#

whats the issue?

zealous lagoon
#

okok I think I'll explain my current solution and I think it'll be more clear

rigid island
#

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

zealous lagoon
#

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.

heady iris
jaunty sleet
heady iris
#

Yeah, the actual position of the object has nothing to do with where it gets drawn on the screen

jaunty sleet
#

what do you mean?

heady iris
#

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)

zealous lagoon
jaunty sleet
heady iris
#

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

jaunty sleet
#

oh ok, that makes sense

heady iris
#

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

jaunty sleet
#

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

rigid island
jaunty sleet
heady iris
zealous lagoon
heady iris
#

This one gets physically positioned in front of the camera -- and it gets rendered along with the rest of the scene

jaunty sleet
#

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

heady iris
#

(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

rigid island
zealous lagoon
rigid island
zealous lagoon
#

there's no stage editor or anything like that

rigid island
zealous lagoon
rigid island
zealous lagoon
heady iris
#

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

zealous lagoon
zenith acorn
#

Should I use the unity's ObjectPool<T> or create my own with a dictionary and queue

heady iris
#

I've had a good time with unity's pool classes

#

although I mostly use them for collections, not unity objects

leaden ice
zenith acorn
heady iris
#

okay, so you should have multiple pools!

zenith acorn
#

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

leaden ice
#

You can put the pools themselves in a dictionary keyed by the projectile type

#

No need for different scripts per gun

hexed pecan
#

I personally just map an enum value to each projectile base type

heady iris
#

Keyed by the projectile prefab, even!

zenith acorn
#

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

heady iris
#

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

zenith acorn
#

Cause the pool is the Bullet script

#

Not the bullet object?

#

I'm kinda confused at this part

heady iris
#

ObjectPool<Bullet>

zenith acorn
heady iris
#

This is an object pool that handles Bullet objects

zenith acorn
#

Isn't the Bullet a script of the object?

heady iris
#

Bullet is, presumably, a class you defined

#

one that inherits from MonoBehaviour

zenith acorn
heady iris
#

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);
}
zenith acorn
heady iris
#

Multiple unique kinds of projectiles, you mean?

#

like "smg bullet" and "grenade"

zenith acorn
heady iris
#

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

plucky karma
#

Ideally, you'd use Interface for IBullet, which you can label GiantBullet or SmgBullet class?

cosmic vector
zenith acorn
heady iris
plucky karma
#

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.

zenith acorn
#

Thank god there's a good community

#

Now I know how it works

heady iris
#

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

zenith acorn
#

I really didn't know

#

I just know that T type can be used inside a class where you don't predefine the type

vestal arch
#

that's generics as a concept

heady iris
#

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 TArgs and returns a TResult

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

plucky karma
#

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.

heady iris
#

"infer a umbrella term of shotgunning methods implementation" is a confusing phrase

zenith acorn
#

what is even an umbrella term

#

and shotgunning method

#

That's deep

heady iris
#

well, "umbrella term" would mean something that covers a lot of ideas

plucky karma
#

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.

languid hound
#

Dang the more you know I suppose. I didn't even know that had a name

heady iris
#

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!

plucky karma
#

Learn it from working experience in the industry. 🤷‍♂️

heady iris
simple egret
#

Yep never heard of it either apart from the debugging term

zenith acorn
simple egret
#

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 :)

languid hound
#

I love delegates

zenith acorn
#

There's something called DictionaryPool

#

Hopefully it works

heady iris
#

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

zenith acorn
#

How is that different from the normal list?

#

So you get the list from the pool

#

instead of creating one?

heady iris
#

It lets you re-use lists

zenith acorn
heady iris
#

that way, you aren't allocating a new list and then causing reallocations as you fill it up

zenith acorn
heady iris
#

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.

zenith acorn
tiny delta
#

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:

lilac frost
# tiny delta

I did something similar and created a "PlayerSetup" script that initialises all of the different components

leaden ice
tiny delta
#

I don't think the singleton pattern can work since this is a multiplayer game, though I could be wrong

lilac frost
#

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...
     }

}
}

tiny delta
#

Both

leaden ice
#

I mean some things can certainly still be a singleton - e.g. the "character manager"

lilac frost
# leaden ice or online?

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

tiny delta
tiny delta
#

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

indigo tree
tiny delta
#

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

lilac frost
leaden ice
tiny delta
#

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?

hardy pasture
#

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.

leaden ice
#
public class MyDriver : MonoBehaviour {
  public static event Action OnUpdate;

  void Update() {
    OnUpdate?.Invoke();
  }
}```
hexed pecan
#

I wonder if you could avoid MB by modifying the playerloop

leaden ice
#

But then you're dabbling into ECS which is a whole new world...

hexed pecan
#

If you could hook an event there somewhere

leaden ice
hardy pasture
hardy pasture
#

Or is there a way to have this MonoBehavior classes in all the scenes?

leaden ice
hardy pasture
#

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.

hardy pasture
hardy pasture
ivory cove
#

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.

hexed pecan
#

Might be both a camera issue and a character movement issue

#

How is your character moving?
If rigidbody, is interpolation enabled?

ivory cove
rigid island
# ivory cove

iirc update method should probably be Smart update or fixedUpdate

hexed pecan
#

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

rotund lake
#

yo Osmal

ivory cove
rigid island
#

normally physics dont run on clients but are kinematic and simulated by server

#

havent used Fishnet though

ivory cove
ivory cove
# hexed pecan I suppose this is related to the networking?

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

hexed pecan
#

Nicee

#

Make sure to always read those message boxes in inspectors

leaden ice
leaden ice
plucky karma
tiny delta
#

I don't get what you mean

plucky karma
#

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.

heady iris
plucky karma
#

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.

heady iris
#

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

plucky karma
#

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.

heady iris
#

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

tiny delta
tiny delta
heady iris
#

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

tiny delta
#

What do you mean by "concerns"?

heady iris
#

basically, what each of your classes's jobs are

tiny delta
#

Oh gotcha, that's true

heady iris
#

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

tiny delta
#

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

heady iris
#

circular dependencies aren't the end of the world, but you can often avoid them

tiny delta
#

Yeah, just in general my whole script there was awfully written there

tiny delta
heady iris
#

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

tiny delta
#

Makes sense.

heady iris
#

But in this case, you could totally have a StatusSpell that just contains a list of status effects to inflict

tiny delta
#

So I assume I should get rid the of idea of a class that has references to each gameobject then, correct?

heady iris
#

that'd be like a phonebook, I suppose

#

a big directory of every single thing anything might want to talk to

tiny delta
#

Yes, exactly, that was what my plan for how I'd give out references was

heady iris
#

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

tiny delta
#

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

heady iris
#

aeugh

tiny delta
#

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

somber nacelle
#

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

tiny delta
#

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

lyric verge
#

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

heady iris
#

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

gleaming gate
#

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.

indigo tree
gleaming gate
#

Well I plan to make a custom UI for this without editing the stats directly.

rigid island
#

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

cold parrot
rigid island
#

most likely JSON would probably be more than sufficient

gleaming gate
cold parrot
#

is it for saving stuff to disk? for querying at runtime? for multiplayer persistence?

rigid island
#

an RPG is vague

#

yes what exact usecase is for specifically ?

cold parrot
gleaming gate
#

I do know why. But when making functions I need to store the data somewhere.

cold parrot
#

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

gleaming gate
#

Yes that's more like it. I need to access the stats in a quick and easy way.

cold parrot
gleaming gate
#

Not when running. When I'm in battle, chances are I loaded all the stats already and don't need to change.

cold parrot
#

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.

summer heart
#

And yes a save system

gleaming gate
cold parrot
#

i think what you call a database is basically "a game's systems"

gleaming gate
#

Like I can see how the categories would go and how SQL and Json would help.

gleaming gate
cold parrot
#

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

gleaming gate
#

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.

cold parrot
#

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

gleaming gate
summer heart
gleaming gate
flat hill
#

If the data doesn’t change scriptable objects should work fine

summer heart
#

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.

somber nacelle
#

please don't use PlayerPrefs for save data. it is not really meant for that and just bloats the user's registry

gleaming gate
gleaming gate
heady iris
#

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

somber nacelle
# gleaming gate I know full well that it's not good for games of decent scale.

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

heady iris
#

yeah, the "player" in "PlayerPrefs" refers to the built game

#

it's the Player, rather than the Editor

rigid island
#

PlayerPrefs also good for storing data like cookies or sessionsIDs

#

not for long term storage like savefile

gleaming gate
heady iris
summer heart
# gleaming gate Does anyone know of any good and bad practices to for making a database for an R...

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)

heady iris
#

i had a long rambling discussion on this recently

gleaming gate
#

I guess so. Was thinking going between screens.

heady iris
#

I included an example from a game I was working on a year ago or so

gleaming gate
#

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.

narrow sapphire
somber nacelle
#

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

heady iris
narrow sapphire
#

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

heady iris
#

You will just annoy people like me, who will then spend several hours reverse-engineering your format out of spite

heady iris
#

you can't modify assets in the built game

narrow sapphire
#

What has that got to do with what I said

#

Sorry I don’t understand

heady iris
#

oh, you're talking about a database of game data, not necessarily saves

narrow sapphire
#

I thought we were talking about things like item stats

heady iris
#

Right.

narrow sapphire
#

Ye ye

heady iris
#

I would still not think at all about this. I would focus on what's actually good for the game developer

narrow sapphire
#

In that regard I think sos and json are like equally as good so for me things like this are the decider

heady iris
#

If a person wants to cheat at a singleplayer game, then...go nuts

somber nacelle
narrow sapphire
#

Ah fair I’m not really familiar with how building works

heady iris
narrow sapphire
#

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

somber nacelle
#

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

gleaming gate
#

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.

heady iris
#

also, consider modding support

#

random example: Brigador is super nice to modify. The entire game is pretty much just JSON

rigid island
#

or online APis

#

almost all web languages can easily work with json

gleaming gate
#

Don't really need modding support for an RPG.

rigid island
#

i think the point was that its that flexible to allow that easily

#

the most basic modding modify values in a keyvalue pair system

gleaming gate
#

But ye I'm going to do it in SOs it seems.

summer heart
verbal hazel
#

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?

zenith acorn
#

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

plucky karma
somber nacelle
#

it expects a Func<GameObject>, you are passing it the return result of your CreateBullet method (which is just a GameObject)

somber nacelle
#

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

zenith acorn
#

Do I need to manually make a function for createexploding bullet and createnormalbullet or smth?

plucky karma
somber nacelle
#

or you can just slap () => on the beginning of the argument

somber nacelle
plucky karma
#

You were probably thinking of Action<T> which takes in an argument, but this function expects Func<T> which returns you a value.

zenith acorn
somber nacelle
somber nacelle
#

even if the method expected an Action, that would still be incorrect

plucky karma
somber nacelle
#

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.

zenith acorn
somber nacelle
#

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

plucky karma
zenith acorn
somber nacelle
#

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

cosmic rain
somber nacelle
# zenith acorn That helps

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

verbal hazel
somber nacelle
cosmic rain
#

Using a dedicated GPU profiling tool, like PIX, could also be helpful

zenith acorn
#

unless it breaks again

#

😅

faint hornet
#

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.

somber nacelle
#

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

faint hornet
somber nacelle
#

all of this happens before it is rendered. can you be more specific about what you are seeing or provide a video

faint hornet
#

i want to set the transforposition to instatiate in the Translate spot .5 meter up

faint hornet
somber nacelle
#

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.

faint hornet
#

i'll take two screnshots 1 sec

somber nacelle
#

is it actually disabled in the prefab though?

faint hornet
#

yes

somber nacelle
#

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

faint hornet
somber nacelle
#

so do it then?

faint hornet
#

idk how to?

somber nacelle
#

which part of that are you unsure how to do

faint hornet
#

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?

somber nacelle
#

you have a transform though, it's literally this component's transform

rain minnow
faint hornet
somber nacelle
#

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

rain minnow
vestal arch
faint hornet
vestal arch
#

they're translating the transform, then setting the velocity of presumably a rigidbody

somber nacelle
faint hornet
somber nacelle
#

no, that is not relevant

rain minnow
faint hornet
#

not everytime.. i didn't earlier

rain minnow
#

are you moving the bullet by manipulating the transform or using physics?

#

whichever one you choose, it must remain the same . . .

somber nacelle
#

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 🤷‍♂️

rain minnow
#

since they assign the bullet position, they can just use that position and add the code used in Translate to move it . . .

somber nacelle
#

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

rain minnow
#

facts. i keep forgetting it's Space.Self by default . . .

faint hornet
stoic echo
#

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!

rain minnow
zenith acorn
#

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

rapid brook
#

@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

zenith acorn
#

I'm using the urp

rapid brook
#

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

zenith acorn
#

Okie thanks I will check it out

rapid brook
#

If you have any question don't hesitate

plucky inlet
#

There is also a renderfeature (hope ita still there) to swap materials on depth check in urp automatically

zenith acorn
rapid brook
#

Yes you can do the depth check with higher, less or equal if I recall correctly

strange cargo
#

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.

pearl burrow
#

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

somber nacelle
#

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

pearl burrow
pearl burrow
somber nacelle
#

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

pearl burrow
#

ok so i have gameobject instantiated at runtime, each having a script that fire this coroutine

rapid brook
#

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

somber nacelle
somber nacelle
rapid brook
rapid brook
pearl burrow
#

why? unity isnt multithreaded anyway if you dont force it

#

i mean doesnt everything runs on a single thread?

rapid brook
#

It does but you will have a hard time with immediate checks in a couroutine if you yield

somber nacelle
pearl burrow
#

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?

somber nacelle
pearl burrow
#

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?

somber nacelle
somber nacelle
pearl burrow
#

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

rustic ember
#

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?

knotty sun
rustic ember
wintry crescent
#

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?

knotty sun
wintry crescent
#

I think I even remember the thing I was working on, when I learned it

zenith acorn
# rapid brook One way I could see you do this is by having having a separate layer for the obj...

So I'm following this tutorial down below, but it seems that it only works with shaded smooth object

https://www.youtube.com/watch?v=Bm6Bmcjd1Mw

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...

▶ Play video
#

and when I try with object that are not shaded smooth

#

This happens

rapid brook
#

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?

zenith acorn
#

like if I add this to a capsule it works fine

zenith acorn
#

I'm not actually sure about that

rapid brook
#

Wait I'll find you a better shader hold on

zenith acorn
#

Okiee

rapid brook
#

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...

▶ Play video
#

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

zenith acorn
#

woahh looks good

#

lemme try it

rapid brook
#

Okay if you have any question, don't hesitate again

zenith acorn
#

well can I change the color though?

rapid brook
#

Yes

zenith acorn
#

Cause I want to make it obvious for the player

#

noicee

cold parrot
rapid brook
#

True but for his purpose wouldn't that fill the same functionality

cold parrot
#

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

rapid brook
#

"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

cold parrot
#

the unfortunate situation in U6, i think, is that there just isn't a good free outline shader/tutorial around

rapid brook
#

Did he say he was using Unity 6?

cold parrot
#

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

rapid brook
#

Haven't touched Unity 6 so I wouldn't know, is it that different?

cold parrot
#

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)

rapid brook
#

Seems very inconvenient. Is the render graph the new equivalent for shadergraph?

rapid brook
#

Thanks I'll look it up

mossy drift
#

Someone from here knows about unit test? twt

cold parrot
#

i don't know of any free implementation, that works, which doesn't use the (inefficient) gaussian blur method

kind willow
#

So, can I check if webgl game was launched on mobile/anything havin sensors really, or not, without using a bit of javascript?

unique mortar
#

Hey, Im a beginner can someone lmk how easy or difficult would it be to develop multiplayer games?

unique mortar
#

like a room with multiple players in that room and them doing some tasks that gains them points etc.

cold parrot
#

how competitive? for your friends only?

unique mortar
#

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.

rapid brook
#

@zenith acorn Anikki might have a better shader for your needs

wheat spruce
unique mortar
wheat spruce
unique mortar
#

why so?

cold parrot
kind willow
cold parrot
#

the 15 alone is a problem that makes it impossible

hexed pecan
#

15 people not knowing what they are doing will result in incredible spaghetti code

cold parrot
#

you'll spend 90% of your time talking and fixing miscommunication issues

knotty sun
# unique mortar ohh

if you were doing 10 hours/day for 15 months you might just make something playable

wheat spruce
#

I havent really used directives, never had the need. But thats my understanding of what theyre for at least

thin aurora
zenith acorn
#

I'm testing it out

#

but the setting is different with mine

#

like mine looks like this

wheat spruce
#

plenty of code ive seen has stuff like #if xbone #if playstation #if osx

zenith acorn
#

and there's no pass index

kind willow
knotty sun
kind willow
#

but I don't know the details

kind willow
wheat spruce
# unique mortar why so?

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

cold parrot
zenith acorn
#

Cause I'm new to this

#

🥲

cold parrot
#

but it has all the code at the end

#

you just have to figure out how to implement it in your render pipeline

hexed pecan
#

Oh, bgolus, I recognize that name from the forums

#

Didnt know he has a blog, neat

wheat spruce
#

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

kind willow
zenith acorn
#

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

unique mortar
#

OHh

unique mortar
#

thanks

zenith acorn
#

and after you guys finish with your part someone need to combine them 💀

kind willow
#

there are version controls for unity, kinda...

zenith acorn
cold parrot
#

project management is not a unity specific problem and version control wont fix it

#

15 beginners using git will just be a mess

zenith acorn
#

Will this method work?

cold parrot
#

this kinda works

kind willow
#

so anyway sorry for bumping what is the most reasonabel way to decide if you enable mobile sensor controls or not
for WebGL

cold parrot
#

at least it does up to unity 2022 (URP 14)

kind willow
#

I saw someone making a tiny plugin for that

kind willow
#

which is... okay but it touches javascript

cold parrot
tardy path
#

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

hexed sorrel
#

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?

hexed pecan
#

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

tardy path
hexed pecan
#

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.

kind willow
#

iPad is the case

#

yeah quirky stuff

tardy path
#

could you give me an example of how that is used?

sacred sinew
#
    rb.AddForce(HorizontalSpeed)
}```
tardy path
tardy path
zenith acorn
languid hound
#

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)

https://pastebin.com/nGADaDNr

hexed pecan
tardy path
#

does that change much?

hexed pecan
#

Same principle applies

tardy path
#

for a specific direction that is

hexed pecan
#

You can think of them as caps, sure

#

They form the velocity that you want to reach. Not much else to it.

tardy path
#

i.e leftSpeedCap and rightSpeedCap or something

fickle crown
#

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

leaden ice
fickle crown
leaden ice
#

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

fickle crown
#

yes, I don't want the ballls to move in the Y axis, only on the floor, think of pinball or something like that

leaden ice
#

Ok

frank sequoia
#

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?

fickle crown
#

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

languid hound
#

Also you should probably try <= MinimumSpeed not <

frank sequoia
fickle crown
languid hound
#

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

fickle crown
#

is there something set up wrong? ...

languid hound
#

Wait no sorry again I need to follow along more

fickle crown
languid hound
#

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

fickle crown
#

I have removed that material as well to try it out

stoic echo
heady iris
#

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

stoic echo
#

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?

heady iris
#

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.

stoic echo
#

I see, thank you for explaining me the difference, but does Git have a data limit?

heady iris
#

no, beyond Git slowing down when you work with lots of huge files

stoic echo
#

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?

eager tundra
#

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

heady iris
#

You should then version control everything that isn't ignored

heady iris
#

I don't use it in my games. I just shove everything into Git!

eager tundra
#

yeah, you can move it later on demand if the project gets big enough

stoic echo
#

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?

haughty plinth
#

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?

stoic echo
#

and how can i update my game everytime she makes any changes and vice versa? i think thats with the unity version thing correct?

eager tundra
eager tundra
stoic echo
#

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?

eager tundra
#

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

heady iris
#

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

eager tundra
#

using a graphical interface can make it much less intimidating (GitHub Desktop or something similar)

stoic echo
#

alright, thank you guys! ill take a look at git!

zenith acorn
#

I'm using the unity's new input action however for some reason when I presses R there is error now

stoic echo
#

hey guys! another question is, will git work well with scenes? im seeing a lot of comments about it

knotty sun
heady iris
#

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)

leaden ice
#

Looks like you had an exception thrown inside your listener function

#

Are you using Visual Scripting?

zenith acorn
#

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

#

😭

leaden ice
#

Show how you hooked up your code to the input system

zenith acorn
leaden ice
#

I think you made a mistake there somewhere

leaden ice
leaden ice
#

And show how you hooked the input system up to it

zenith acorn
leaden ice
#

Already suspicious

zenith acorn
#

hold up yeah

#

why is there visual scripting

leaden ice
#

There's a lot of weird things there

#

remove them

zenith acorn
#

I'm using this

leaden ice
#
using System.Runtime.CompilerServices;
using Unity.VisualScripting;
using UnityEngine.Experimental.GlobalIllumination;
#

get rid of these

heady iris
#

probably just over-aggressive using-inclusion

#

thank you, VSCode, for dragging in a random Localization namespace

#

i didn't want my game to compile

leaden ice
#

Show the stack trace for this one too @zenith acorn

zenith acorn
leaden ice
#

your IDE included them when you typed something

zenith acorn
#

I swear to god like it wasn't there

raven basalt
#

How do I brighten a ui image through script?

leaden ice
zenith acorn
leaden ice
#

Looks like your InputManager script, line 107

zenith acorn
#

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

leaden ice
#

that'll do it

heady iris
#

The question remains why the visual scripting system is involved at all here

raven basalt
# leaden ice change its `color`

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;
   }




heady iris
#

That would make sense

leaden ice
zenith acorn
#

it just got included randomly

heady iris
#

ah, yes, that's exactly it

leaden ice
#

especially if they are already "full bright"

zenith acorn
#

like I didn't even touch viusal scripting at all

heady iris
#

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)

zenith acorn
#

loll

heady iris
#

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

zenith acorn
#

I do have a getcomponent inside my script

heady iris
#

An extension method lets you create new methods for existing types

zenith acorn
#

maybe that's the reason

leaden ice
#

And if the brightness is already 1, it won't do anything

zenith acorn
leaden ice
#

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
zenith acorn
#

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?

leaden ice
# heady iris it sounds fine to me tbh

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

leaden ice
#

WeaponType is not inside WeaponData

#

it's on its own

#

You would just write WeaponType weapon;

zenith acorn
#

But I tried directly WeaponType

#

and it is red

leaden ice
#

"it is red" is vague

#

read the actual error message

#

and show what code you wrote

zenith acorn
#

okiee

#

my bad

heady iris
#

that's more succinct

#

I'm so used to using HDR colors at all times that it didn't even come to mind

halcyon swallow
#

why arent the serialised feilds for theese two game objects showing up?

modern creek
#

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.

halcyon swallow
#

ah right

#

annoying how subtle that is

#

shows up green and everything

knotty sun
marble pike
#

gotta pass in 'r' not 'ray' as you named your ray variable 'r'

halcyon swallow
#

i know i copied code that said Ray r and code that used Ray ray :D

knotty sun
#

very good reason not to copy/paste

halcyon swallow
#

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

leaden ice
#

Ray is a type

#

RaycastHit is a type

knotty sun
#

ok, but at which point in this process do you think your brain should be involved?

leaden ice
#

This seems like an "I don't know C# well" thing, not an "I don't know raycasting" thing

halcyon swallow
halcyon swallow
knotty sun
leaden ice
halcyon swallow
#

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

heady iris
#

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

halcyon swallow
#

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

heady iris
#

Yes -- it's strictly a point and a direction

halcyon swallow
#

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

leaden ice
#

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.

heady iris
#

do you have an example handy?

heady iris
leaden ice
#

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 😬

soft shard
# tardy path Ive looked around for other ways to move the player, like body.addForce, that do...

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

halcyon swallow
#

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

knotty sun
soft shard
halcyon swallow
leaden ice
halcyon swallow
#

seems kinda funny that the thing named drawray cant take ray as an input directly and you need to split it

leaden ice
#

The biggest travesty is that DrawRay and Raycast have different shapes

halcyon swallow
#

different shapes? wdym

leaden ice
#

Different API shapes

halcyon swallow
#

oh right

leaden ice
#

Raycast accepts (origin, direction, distance)
DrawRay accepts (origin, <direction and distance in one>)

halcyon swallow
#

just make it both accept a ray and position rotation seperate

leaden ice
#

they just.. haven't.

wheat spruce
#

I'd imagine the Ray being a really simple struct is why they havent needed to

leaden ice
#

Right but - Raycast accepts either/or.

#

so they did it in one place, and not another

halcyon swallow
wheat spruce
#

end of the day it is a debug function

spare dome
#

Also it is not a huge deal, just give it aa origin and direction and you will be fine

leaden ice
#

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.

wheat spruce
#

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

karmic stratus
#

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?

hidden compass
#

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..

wheat spruce
#

planar merging is the name for combining triangles that exist on the same flat plane

hidden compass
wheat spruce
#

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

leaden ice
#

Probably just "Mesh decimation" or "mesh optimization"

#

and specifically this is an optimization regarding coplanar triangles

wheat spruce
halcyon swallow
wheat spruce
#

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

halcyon swallow
wheat spruce
#

this seems like it would be suitable @karmic stratus

hidden compass
#

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

wheat spruce
#

it might also be worth doing this in a ComputeShader, that could generate all the point data far quicker than the CPU ever could

heady iris
#

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

wheat spruce
#

not simplifying, just running the initial code to create the points in the code from earlier

heady iris
#

Ah, I see

wheat spruce
#

was going to follow up about that before you replied to me 😅

hidden compass
heady iris
#

watch out, i'm coming in at the speed of light to answer the wrong question 💪

hidden compass
hidden compass
wheat spruce
#

doesnt unity have some sort of limit on the number of vertices its able to turn into a mesh?

hidden compass
#

im reading 65,535

wheat spruce
#

but compute shaders arent really that complicated, they seem scarier than they really are

heady iris
#

you can switch to 32-bit indices

hidden compass
#

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

hidden compass
hidden compass
#

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

robust trout
#

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 ^

leaden ice
#

generally games use a simplified cast or a couple casts for such things

#

it doesn't have to match the visuals perfectly.

hidden compass
# robust trout I'm trying to write my logic for melee weapons in my game. Theres a variety of w...

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...

▶ Play video
#

maybe worth just lookin at

robust trout
#

I'm pretty much trying to copy Kingdom Come Deliverance if you've ever played that

hidden compass
#

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