#archived-code-general

1 messages Β· Page 197 of 1

somber nacelle
#

but why

heady iris
#

and it doesn't restore the old RNG state afterwards

#

see SplineInstantiate.cs

somber nacelle
#

you should 100% report that as a bug

heady iris
#

I thought I was going crazy when an enemy performed a 33%-chance attack 30 times in a row

#

URP 14.0.8 also sets the RNG state, based on frame count

#

in PostProcessUtils.cs

#

that's also bad.

somber nacelle
#

shit at that point i'd just start using System.Random to avoid random packages from screwing with the rng

heady iris
#

static moment

somber nacelle
#

shame there's no .net 6 yet for that nice convenient Random.Shared

heady iris
#

i'm not sending them my entire project, so I guess I should make a demo

#

Can't reproduce it in a new project so far. I'll have to embed the package and poke around a bit, I guess

#

notably, I have no components of type SplineInstantiate in the scene in my game..

void turtle
#

Does anyone know how to fix the backround fps of my application? it runs on less than 1 fps and I cant really test stuff in multiplayer. I already checked the NVDIA Control Panel and Player Settings

heady iris
leaden ice
void turtle
#

I tried that but It didnt work 😦

tawny elkBOT
#
Posting code

πŸ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

πŸ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

orchid bane
#

We want to make a MonoBehaviour which will have a reference to a system and all the data needed for that syste. For example if it references SceneChangeSystem then it should have a scene's name, if it has a reference to DropThingsSystems then it should have a DropTable. We want it to be only 1 kind of Monobehaviour. It all will be saved to json. We consider the optiong of using uuids as references. Can you think of any way to do something like that?

hard viper
#

I'm trying to figure out how to set up VFX. I set up the pipeline and everything. I have a VisualEffect component on one gameobject (prefab). Here is what I am seeing:

  1. Dragging prefab into scene => yes VFX
  2. Instantiating prefab programatically => no VFX
    Any ideas as to why this is hapenning
heady iris
#

Oh my god it wasn't Splines' fault

#

i mean

#

Splines is still buggy here. Just reported that issue.

#

But it wasn't causing the issue.

limber dust
#

so i have this pagecollect text object dragged into this script, but when i run my game it disappears???

heady iris
#

It's PostProcessUtils.cs in com.unity.render-pipelines.universal@14.0.8

#

It seeds the RNG with the current frame count

somber nacelle
limber dust
#

i will check

heady iris
somber nacelle
limber dust
somber nacelle
#

yes, remove that line from Start

limber dust
#

okay i will try

somber nacelle
#

that's literally reassigning it to the Text component on this object. which does not exist so it assigns null

sterile mist
#

Hey can anybody help me w a code?

heady iris
limber dust
somber nacelle
sterile mist
sterile mist
#

Am I in the right chat tho

somber nacelle
#

is it a general code question or a beginner code question? if it is the former, then yes. if the latter then #πŸ’»β”ƒcode-beginner would be more appropriate

sterile mist
#

Idk if it counts as beginner

#

Yk what I'll just ask it in beginner just to be sure

#

Ty

heady iris
#

very funny how I randomly found a Splines bug by accident

#

well, that was an annoying two hours, but at least I know what's going on now

thick socket
#
Tag: tag name is null or empty.
UnityEngine.StackTraceUtility:ExtractStackTrace ()
ForwardDetector:OnTriggerEnter2D (UnityEngine.Collider2D) (at Assets/Scripts/Enemy/Trigger Checks/ForwardDetector.cs:15)
#
 private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag(WallTag) || collision.gameObject.CompareTag(WallTag2))
        {
            _enemy.forwardDetector = true;
        }
        else if(collision.gameObject.CompareTag(PlatformTag) )
        {
            _enemy.forwardDetector = false;
        }
    }
#

so apparently if I have a Collider untagged unity gets mad?!?!?

heady iris
#

no, WallTag or WallTag2 are null or empty

#

check their values.

thick socket
#

Do the tags have to exist?

#

or can I not have a tag made thats called "test"

#

and have WallTag = "test"

heady iris
#

ok, cool, but are WallTag or WallTag2 null or empty when you use them?

#

check by logging them

#

If WallTag is a public field, then you probably added that field initializer after you already added this component to something

somber nacelle
# thick socket Do the tags have to exist?

the strings you pass to CompareTag must be not null and not just whitespace. they also have to be an existing tag. the main benefit of using CompareTag is that an error will be thrown when the tag does not exist

heady iris
#

the value shown in the inspector is what's serialized

#

that will overwrite whatever the default value of the field is

thick socket
#

that was the issue, I just put a random tag in 1 spot cause I just didn't need it and it was throwing errors when I didn't have one πŸ˜„

somber nacelle
#

well no, the error you received is because the string was either null or empty. you'd get a different error if the tag doesn't exist

heady iris
#

Tag: tag name is null or empty.

#

that's the error.

heady iris
#

log both values before that line of code runs

#

look at what gets printed out

somber nacelle
#

use this line to see both of those tags printed: Debug.Log($"Tags '{WallTag}' and '{WallTag2}'");

thick socket
#

I added "test" to my tag list and errors gone now

#

Β―_(ツ)_/Β―

heady iris
#

okay, but did you do what we both asked you to do?

#

WallTag2 is null or empty

#

The conditional short-circuited because CompareTag(WallTag) returned true

thick socket
#

Okay but like did you hear that I dont have an error

heady iris
#

So it skipped CompareTag(WallTag2)

thick socket
#

So they arent null

heady iris
#

No, you don't have an error because || short-circuits.

#

If the first half of the conditional fails, the second half will throw an error when that empty WallTag2 string goes in.

thick socket
somber nacelle
#

yeah until you realize that we were actually right about one of those strings being null or empty

heady iris
#

we are trying to get you to understand what actually went wrong

#

You were originally getting two errors

#

one for a bogus layer name, one for the layer name being null or empty

#

(i just went and checked how this would behave)

#

WallTag2 is still null or empty, but there's no error because || short circuits and prevents CompareTag(WallTag2) from executing

#

You will suddenly start getting errors again if you bump into something that isn't tagged "wall"

hard viper
#

I'm still confused with my VFX issue. I have a prefab with a VisualEffect component. If I drag the prefab into the scene, the VFX plays. If I instantiate it programatically, it does not play, even if I call .Play() on the component.

#

Removing the component during runtime and adding it back in does nothing.

heady iris
#

what about toggling the game object or the component?

hard viper
#

also no effect

heady iris
#

I had a bug once where I was using GetComponentInChildren<Renderer>() to fetch a mesh renderer

#

at some point, it started grabbing the visual effect renderer instead

#

and that wound up breaking the effect

#

(I was messing with the renderer a fair bit)

#

doesn't sound like that's what is happening here, though

hard viper
#

this is what is in the component during OnEnable

orchid bane
#

How to show one object inside another one with Odin?

hard viper
#

I did a little more testing. The particles ARE being made. They just aren't rendering

dawn mauve
#

Has anyone done an event heavy version of a their game before?

For me it makes the most sense to do "event storming" (kinda like brainstorming except trying to find events in a software system) and try to find what events occur in what I want to build. I have a tight definition of event to mean "an interesting happening in the game, phrased always in past tense" (YMMV).

Just curious what experiences others have had.

hard viper
#

I try to have a few singletons with several very frequently used events, so events can all be coordinated

#

I also have a bunch of events going around, but a lot of things get tied to something like "OnEnterPlay", "OnLevelLoad"

#

which then get OnLevelLoadEarly, OnLevelLoad, OnLevelLoadLate so I can orchestrate who does what when

hard viper
#

dude this Unity VFX package is garbage. this is the second time the VFX graph file it makes just gets corrupted during normal use, and causes repeated crashes

#

second time in 1 hour

limpid owl
#

i saw a unite 2017 video where they used scriptable objects as channels or medium instead of hard rigid reference to classes and i think it's a good method, the problem is that each object that need the SO require a drag and drop from the inspector so i was thinking if DI container is good to inject all so objects

#

UI ---> PlayerMoney <----- other classes

#

Scriptable Objects are an immensely powerful yet often underutilized feature of Unity. Learn how to get the most out of this versatile data structure and build more extensible systems and data patterns. In this talk, Schell Games shares specific examples of how they have used the Scriptable Object for everything from a hierarchical state machine...

β–Ά Play video
wispy wolf
#

I can never remember vector math terms. I suppose this is kind of like project(), but that's not doing that I want.

I have a vector3, say (4, 0, 1) to make it easy. I have a normal (1,0,0), again very simple to make it easy.. What I want is the result of first vector that excludes the normal. So in this case the result should be (0,0,1), because all of the vector magnitude along the normal (1,0,0) has been ignored.

What's the term for this?

lean sail
wispy wolf
#

It won't always be zeros

uneven vortex
#

so uh, im attempting to make a 2d game for my friends, and whenever its on office 1 it thinks its on office 2 im new to unity, so i dont exactly know how to fix this

limpid owl
#

(4,0,1) x (1,0,0) = (4,0,0)
then
(4,0,1) - (4,0,0)

don't know about this not sure i understand u well
@wispy wolf

uneven vortex
lean sail
# wispy wolf It won't always be zeros

I dont believe ive seen such an equation, you may have to elaborate more because ive never heard of "excluding" a normal and ive done a few lin alg courses.
Maybe what GMA posted above is what you want, although you cannot multiply vectors 1x3 * 1x3
you have to multiply each individual component

limpid owl
uneven vortex
#

no, they are in different areas

limpid owl
uneven vortex
#

one second

#

basically when i try to touch the button for the first office (left) it thinks im on the second office (Right). I have no clue what other details im supposed to give

#

found out the issue

#

nvm

hard viper
#

i figured out my particle issue. It was caused by orienting to face camera. No idea why that was the culprit.

eternal wagon
#

somehow my game view scales to 1.8x everytime I hit "Play"
Anyone know what's the reason?

rigid island
eternal wagon
#

nope.

leaden ice
leaden ice
#

ok that's good

#

idk what the problem is then lol

eternal wagon
#

it started happening recently. when I added LevelPlay and changed platform to android

cosmic rain
#

Or otherwise a mobile device resolution in game tab?

eternal wagon
#

nope. I just set to 16:9 resolution, but it happens in free aspect too.. if I check the low resolution aspect checkbox, my UI adjusts properly. but the lowest scale is then set to 1.8x..
and it looks ugly..

leaden ice
eternal wagon
#

Okay. I think I found a fix.. Unity probably bugged out.. I just changed my editor layout to default and then readjusted all my windows. and it fixed itself.

#

Thank you for all your help Nashville, Praetor, dlich, navarone πŸ™πŸ»

wispy wolf
#

I didn't help but you are welcome lmao

wispy wolf
#

I've been working on something for a bit and I might be overthinking it and going down wrong paths.

Think of a simple racing game. But instead of being flat the track is round, like a tube, and you are racing down it's length. You don't really turn left or right, you just slide around the tube, always facing parallel to the tube.

Easy enough to make the track -- just spawn some meshes on a spline and bob's your uncle. Gravity will always be toward the center of the spline, so I'll do that myself, but that's pretty easy as well. I can get the tangent of the spline at any given location, so I can even orient the car parallel to the track easily enough.

The problem arises from me wanting to have some level of physics like collisions, jumping off ramps, etc. And that's where the whole thing starts to get tricky.

I don't want to write an entire novel about what I've tried. Any pointers?

cosmic rain
#

Sounds fine aside from gravity towards the center of the tube.πŸ€”

wispy wolf
#

Gravity is the easy part, down is always toward the closest spline point and every tick I can add a force.

The part that it tricky is getting the car to follow the track without going nuts on inclines and turns. I can do that easily enough without physics, but I don't want to basically put all the physics stuff back in where I need it

heady iris
#

Vector3.ProjectOnPlane will accomplish that

#

It's equivalent to projecting onto a vector, then subtracting the result from the original vector.

#

i.e. foo - Vector3.Project(foo, bar) equals Vector3.ProjectOnPlane(foo, bar)

scarlet kindle
#

Would it be easy to make a new base project with a correct render setting, and then just copy the old project files in? if a project is botched for working with specific settings?

In my case, I am unable to get 2D URP shadows working in my project, and I don't know how to properly change the settings. Starting a new 2D URP and the shadows work immediately for me, so it's definitely something project setting specific 😦

scarlet kindle
#

I tried making a new Render Asset, and removing all my old ones, reassigning in Graphics & Quality for project settings

latent latch
#

You can export your stuff between projects if you want to do it that way, but I can't expect there's much you need to change to get 2D shadows working.

#

probably some setting you're overlooking

#

Last time I played around with it, it was an experimental package, but I think it's now just included?

scarlet kindle
#

yep, it is definitely strange. setting it up is super fast and easy, as evidenced by my test on a new project....

i have no idea what setting is off in my current project that would stop shadows from being rendered properly

#

im gonna try cloning my proj into the new one... maybe that will work

foggy maple
#

I'm trying to like

spring creek
foggy maple
#

yes

cosmic rain
#

The problem with not expressing your thoughts in one message.

foggy maple
#

lmao me trying to figure out how to phrase it

cosmic rain
#

Then do that first. Then type. Lol

strong geyser
#

can yall help me tf does this mean 😭 (IM NEW TO UNITY SORRYYY LOL)

foggy maple
#

get the aspect ratio to be formatted something like "16x9" and not "1.77777..."
and I am going to deep into this I swear, is there any easy way to format the aspect ratio nicely

like some easy function to reduce the fraction to its lowest whole numbers because I couldn't find really anything googling it for unity and without including unity answers are like "install this package"

cosmic rain
cosmic rain
foggy maple
#

its the 16x9 division

#

im just trying to get the aspect ratio to be user friendly

cosmic rain
#

Showing the resolution is pretty user friendly, but if it has to be in aspect ration, there must be some formula.πŸ€”

foggy maple
#

yes im just sorting the aspect ratios

spring creek
foggy maple
#

yea I think im just gonna have to incorporate my own function

#

I was just hoping there was like some built in function or easy algorithm

hard viper
#

I’m a bit confused as to why a little code block I have costs a lot of computation time. What I do is:

  1. Get the corners of the bounds of a collider as vector2s
  2. Convert the vector2 to vector2int using Grid WorldToCell to get cell coordinates.
  3. Loop from the min and max on x and y to make an array of all cell coordinates that the square collider touches.

This doesn’t seem like it’d be expensive, but 50 calls per fixed update really hurts my frame rate, and I don’t understand why.

#

and each array is usually 4 entries large

scarlet kindle
#

The light just wasn't bright enough to make a shadow... LOL

#

or maybe my bulb was too dim

#

πŸ˜„

cosmic rain
strong geyser
#

I HAVE NO IDEA WHAT THE [Redacted] I DID BUT MY BUILD WORKED πŸ€‘πŸ€‘πŸ€‘πŸ”₯

hard viper
# cosmic rain What do you see in the profiler?

Deep profiler says that that function is only getting called like 40-50 times a frame, but taking like 11-20 ms or some shit. It’s ridiculous. And when I look into the breakdown, it’s split evenly across a bunch of casts and vector operations

leaden ice
#

Sounds like you're just doing a ton of stuff

hard viper
#

i can share tomorrow when I can get it again

#

each one call is maybe like 20 very basic vector operations

#

x40-50 per fixed frame

leaden ice
#

It's running 50x per frame and iterating over a lot of tiles?

#

That can add up

hard viper
#

total tiles usually is 4

#

each collider is a bit smaller than a grid square

foggy maple
#

may just make a "Other" category and put resolutions that dont past the filter in there evil

safe ether
#

I get a null pointer exception when colliding bullet with enemy. I have a takedamage function in my health script, but it doesn't seem to be able to find the Image I have that is used for the healthbar when it is called from an OnTriggerEnter2D function in my bullet script. However, in my health script, I also have an Input.getKeyDown function that also runs the same TakeDamage() function. Using that, unity seems to be able to find my health bar and update it appropiately.

#

this is in my bullet script

#

this is in my health script.

#

Start does show the healthbar in the console

#

and healthamount updates appropiately

#

I am confused as to why the TakeDamage() function seems to see the healthamount variable, but not the image variable.

#

Both are declared: public Image healthbar;
public float healthAmount = 100;

dusk apex
safe ether
#

you just want the error

dusk apex
#

What line is 41 of the health script?

#

It's a message rather than an error so I'm guessing the health bar is null if not caught

safe ether
#

healthbar.fillAmount = healthAmount / 100;

#

is that the line is refering to

dusk apex
#

Where do you assign health bar?

safe ether
#

In unity? If thats what you mean then in the script for health

dusk apex
#

Usual answers would be the inspector or awake/start/misc-method

#

Okay

safe ether
#

I declared it at the top of health.cs if thats what u mean

dusk apex
#

Is this a spawned object?

safe ether
#

as in a clone?

#

the bullet is a clone when it hits the enemy

dusk apex
#

The object with the health isn't a spawned object though correct?

safe ether
#

no

dusk apex
#

So, there's a high possibility that the health bar you've referenced isn't one in the scene

safe ether
#

but my confusion comes from the fact that i can refrence that healthbar from inside the health script

blazing smelt
#

So I changed my project's build target to Android, and now my TMP text appears as pink squares (in the editor, it's fine in the build for some reason). Any idea what's happening here? I tried deleting the package cache and letting it all be re-downloaded (someone said refreshing that stuff should fix it), but that didn't work.
Thoughts?

safe ether
#

but cant seem to access it when outside of the script

#

but i can access the healthamt float just fine

dusk apex
#

Log the name of the object that was hurtcs Debug.Log($"{name} took {damage} damage");

safe ether
#

in my take damage func?

dusk apex
cosmic rain
safe ether
blazing smelt
blazing smelt
#

so I presume there'll just be a bit of a loading screen while it reinstalls everything?

dusk apex
# safe ether
Debug.Log($"{name} took {damage} damage", this);
Debug.Break();//Pauses the Editor```Edited
cosmic rain
safe ether
#

you want me to include the this?

dusk apex
blazing smelt
safe ether
#

i did comment out the healthbar.fillAmount = health / 100

dusk apex
#

After the game is paused, select the message and see which object is highlighted yellow from the hierarchy. Check the component on that object.

blazing smelt
#

cheers thanks mate

dusk apex
safe ether
#

like this correct?

safe ether
#

bullet clone is highlighted in yellow

#

when selecting the exception tho

dusk apex
#

Does it have the health bar reference in it's health bar setup?

#

Apparently it's expected to have health

safe ether
#

so your saying i should declare healthbar in the bullet script?

dusk apex
#

No, I'm saying whatever that's trying to lose health doesn't have the health bar reference. Since you're logging this in Health, it would show what's being damaged and pause the game for you to verify that it's got a proper reference.

#

I'm assuming you've done this logging in Damage and the object damage was the bullet.

#

Where the bullet had a health script and a health bar

#

But threw an error because the bar wasn't set up - obviously not correct.

#

The highlighted object should be an object with the health script

#

Show the damage method

safe ether
dusk apex
#

Logging should be done here

dusk apex
#

Verify that the highlighted object has an appropriate script and referenced field when paused.

#

I'm assuming the field is empty/missing/none etc

safe ether
#

on this log message correct?

dusk apex
#

Looks correct

#

Check it's component and field. The game should have paused after the break message.

safe ether
#

Okay, fixed it. The Health Script in my Enemy prefab didnt have the healthbarimage attached to in it's components

#

Thanks a lot man

#

This is my first time in unity so I probhably overlook a lot of things

dusk apex
#

A small stepping stone. You'll be fine πŸ‘

thin aurora
tawny elkBOT
#
πŸ’‘ IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

β€’ Visual Studio (Installed via Unity Hub)
β€’ Visual Studio (Installed manually)

β€’ VS Code*
β€’ JetBrains Rider
β€’ Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

thin aurora
#

It is currently not properly configured and will not be able to provide the basic help an editor should give you

pure portal
#
public async void LoadTexture2(string fileName, string subFolderName, RawImage image)
    {
        Texture2D tex = null;
        UnityWebRequest www = new UnityWebRequest(GetStorageUrl() + subFolderName + "_" + fileName + "_persp.png");
        www.downloadHandler = new DownloadHandlerBuffer();
        await www.SendWebRequest();
        while (!www.isDone) await Task.Yield();
        if (www.result != UnityWebRequest.Result.Success)
        {
            Debug.Log(www.error);
        }
        else
        {
            // Show results as text
            Debug.Log(www.downloadHandler.text);

            // Or retrieve results as binary data
            byte[] results = www.downloadHandler.data;

            tex = new Texture2D(100, 100);
            tex.LoadImage(results);

            image.texture = tex;
        }
    }

Hello
can someone tell me if there is something wrong with my code?
this code is for downloading a png file from firebase storage as texture then set a raw image's texture with it
the code works until the end but the texture that is attached to the raw image does'nt show anything or blank

#

there is no problem with the link because i can view the image normally

#

and the debug result for the download handler text is like this

#

tried to use downloadhandlertexture previously instead of buffer but return a null instead

cosmic rain
runic kindle
#

can somebody help me? my map is slowly moving upwards

pure portal
#

but for another link it loaded normally

#

oh ok now i just found the problem

#

what a silly mistake
for firebase storage link
i need to add "?alt=media" at the end of the link for it to be working

#

damn

#

at least i can sleep peacefully now

olive field
#

Hello everyone, i am encountering this error in Unity 2021.3.27. It always appears 11-times after a Domain Reload
Do you guys know how to fix it ? if it can be fixed.
I found that somebody recommended disabling lights in scene view, but thats not working for me.

void stratus
#

how can i assign X amount of variables at once ?

#

using random.range

wraith vector
#

What am I doing wrong?

public class PlayerSonar : NetworkBehaviour
{
[SerializeField]
    Player player;

    public List<Transform> enemyList = new List<Transform>();
    private void Awake()
    {
        player = GetComponentInParent<Player>();
    }
    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player") || other.CompareTag("Enemy"))
        {
            player.enemyList.Add(other.transform.parent.transform);
            enemyList.Add(other.transform.parent.transform);
        }
    }

I can see enemyList being update in current script but not on Player script

cosmic rain
cosmic rain
#

Or you're looking at the wrong object.

void stratus
wraith vector
cosmic rain
cosmic rain
wraith vector
cosmic rain
#

But here's one thing to check first: is player a reference to a prefab or an object in the scene?

#

Also, networking might be making things a lot more complicated...

wraith vector
#

prefab that is created when client join the server

cosmic rain
#

You're looking at the instance of this prefab in the scene.

wraith vector
#

but when press the Inspector script, I can see the parent object being selected

cosmic rain
#

Also, "prefab that is created" - is incorrect. An instance of the prefab is being created. Not the prefab itself.

cosmic rain
#

Ah, wait. You said it's a parent?

wraith vector
#

yes

#

since:

[SerializeField]
    Player player;

    public List<Transform> enemyList = new List<Transform>();
    private void Awake()
    {
        player = GetComponentInParent<Player>();
    }```
restive ice
# wraith vector

it is updating the list. you just added your Player script twice.

wraith vector
#

man! TY!

#

I was getting crazy lol

restive ice
wraith vector
#

indeed, ty!

restive ice
#

I have this blend tree which I use to cycle between random 'bored' animations. I control it using a StateMachineBehaviour script.
It it possible to get the number of motions in this blendtree without directly setting the data as an inspector value? If I were to add an animation cycle to this tree, but would forget to change the inspector value, the animation would never play. I'd preffer to set it programatically but getting to the blendtree seems like a bit of a challenge.

cosmic rain
marsh mesa
#

Heya! Im trying to do a certain action in OnTriggerEnter2D, but only when the collission is happening with a certain layermask, but i cant quite figure out how?

#

I tried to do this

#

basically comparing the layermask, and the object's layer

#

but it doesnt exactly work, probably because im comparing a single layer to a layermask

knotty sun
marsh mesa
#

Omg, thanks!

copper rose
#

i have an issue using the tank example from unity with scriptable. Project is working, but for example, i have an scriptable "decision" that search for the player and return true if i can see the player and change state to chase, the problem is when there is alot of enemies and all of them using same scriptable, when one enemy in player range return true, its true also for other enemies, so each enemie have to use a different scriptable "decision" or "action"?

#

so, an state cannot share actions or decision made it with scriptable right?

knotty sun
# copper rose

probably the easiest solution is to use ScriptableObject.CreateInstance to create a local instance of your SO, then write a Clone method to copy the data from the SO Asset into the local instance
That way each tank has their own SO instance to work with

latent latch
#

Usually you use SOs as immutable data and unload it onto an identical class and instead create instances of those, otherwise you'll have to be careful not to write to the original SO data when creating instances of it.

knotty sun
latent latch
knotty sun
# latent latch I recall some funky stuff happening when writing to SOs at runtime, which usuall...

To start with you cannot instantiate a SO, like a MonoBehaviour you cannot use new().
writing to SO's at runtime will not persist data (outside of Play Mode in the Editor) so you have to be careful.
This is why I made
https://assetstore.unity.com/packages/tools/utilities/scriptableobject-pro-218340
which handles making SO's persistent at runtime and also allows runtime created SO's to be persistent

Use the ScriptableObject Pro from SteveSmith.Software on your next project. Find this utility tool & more on the Unity Asset Store.

latent latch
#

Oh, huh. I thought you could instantiate them. I remember reading some argument about which was better to use but that was earlier on when I've not dabbled with them much.

knotty sun
#

no, only CreateInstance is allowed

late lion
#

Instantiate can clone any UnityEngine.Object, including ScriptableObject. But if you want to create one from scratch, CreateInstance is your only option.

somber nacelle
latent latch
#

ok so maybe that was my problem

knotty sun
#

Good point, I had not thought about instantiate, question is is that a deep or shallow copy?

latent latch
#

but if createinstance makes an identical asset, that makes much more sense to use

late lion
#

Instantiate is a shallow copy. References aren't cloned, though serialized classes are, since Unity's serializer treats those as value types. I'm not sure how [SerializeReference] fields are copied.

knotty sun
#

Shallow copy would work for the question asked as long as he is only using primitives

#

Be interesting to see if an Instantiated SO is still linked to the original Asset though

#

because by using CreateInstance you are breaking that link

knotty sun
#

@copper rose I think for you this should work

public MySO originalSO; // Set in inspector
MySO localSO;
...
void Awake() {
localSO = Instantiate(originalSO);
}

There after just use localSO

rocky helm
#

Every time BuyTroop is called from any button, buySlot is equal to buySlots.Length, causing an out of bounds error. This is probably a dumb oversight by me, but I really don't know what it is.

    public void BuyTroop(int buySlot){
        Debug.Log(buySlot); //Always outputs buySlots.Length
        NPCObject npc = buySlotTroops[buySlot]; //This has the same length as buySlots, so this is erroring
        if(npc.cost > money) return;
        //...
    }

    private void BuySlotButtonsSetup(){
        for(int i = 0; i < buySlots.Length; i++){
            //buySlots[i].GetComponent<Button>().onClick.AddListener(delegate{BuyTroop(i);}); //Suggested answer
            buySlots[i].GetComponent<Button>().onClick.AddListener(() => {BuyTroop(i);}); //Suggested answer
        }
    }

None of the buttons have onClicked on anything in the editor, so nothing should be interfering with this, But I did try with giving each of the buttons an onClicked in the editor with "No Function", but surprise surprise, that didn't work. What works tho is if I set the onClicked in the editor to call BuyTroop(n);
The "Suggested answers" mean answers to what I am trying to achieve in https://discussions.unity.com/t/button-onclick-addlistener-how-to-pass-parameter-or-get-which-button-was-clicked-in-handler-method/179151/2

knotty sun
rocky helm
#

But I am very confused

#

Thanks tho

knotty sun
#

The problem is that
BuyTroop(i)
is evaluated at call time
and at call time i == buySlots.Length

#

by using x it creates a unique variable for each call

frigid bone
#

Ill just quietly delete that in shame 🀫

static matrix
#
if (HasReadScripts[d.HasWonKey])
            {

            }

if I haven't actually set HasReadScripts[d.HasWonKey] to anything, will it throw an effor or just presume it false

#

(HasReadScripts is a Dictionary<string, bool>)

static matrix
#

thanks

#

ok so I do need to set it cool

knotty sun
#

If you just want to check use the ContainsKey method

static matrix
#

yeah

static matrix
#

how can I check if an object is a certain class?
Like if I need to iterate through a list of Item can I check if the current item is a Drink that derives from Item

leaden ice
#

I would say in general it's not recommended to do this if you can avoid it though

heady iris
#

yeah, it indicates you have a design problem

static matrix
#

oh noees

heady iris
#

Although, this does feel unavoidable when making inventories.

heady iris
#

you have a bag of Item and you also need to do specific things with specific kinds of items

#

I guess you can keep separate lists of each kind of item.

leaden ice
# static matrix yeah

ideally you do something more like:

foreach (Item item in allitems) {
  item.Use();
}```
And let the item itself decide what "Use" does through polymorphism.
static matrix
#

well yeah I do already do that
however I need to keep track of whether or not the player has read a book

leaden ice
static matrix
copper rose
#

But right now I don’t know why could be better to use so for my states of each enemy

heady iris
#

well, here's a chance to improve the system (:

static matrix
#

yeah

#

rn I have a dict of strings containing the book's name and whether or not the player has read it

leaden ice
static matrix
#

ig on the book's end I can check if the player has read it

#

im stupid yeah

#
 if (!playerStats.GetComponent<Inventory>().HasReadScripts.ContainsKey(HasWonKey))
        {
            playerStats.GetComponent<Inventory>().HasReadScripts[HasWonKey] = false;
        }
        else
        {
            if (playerStats.GetComponent<Inventory>().HasReadScripts[HasWonKey])
            {
                HasWon = true;
            }
        }

(ignore the use of getcomponent, ill fix it later)

thick socket
#
public enum BulletTypes
{
    FireBall=0 
}```
#

is there a way to rename Fireball without destroying every SO that has a SerializedField of BulletTypes?

#

noticed when I renamed enum "items" in the past it basically "wiped" all my SOs

static matrix
#

in visual studio you can highlight it and hit ctrl-r-r and then that renames all instances
but I might not know what an SO is and this wont work at all

heady iris
#

Enums are serialized by value.

#

so if you have FireBall selected in a dropdown, Unity is serializing 0

#

if you update this to

#
public enum BulletTypes
{
  IceBall = 0
}
#

then every place that used to say "FireBall" will now say "IceBall"

#

because that's now the name for the 0 value

static matrix
#

really odd thing, I can't un-hide these

#

idk why

#

I can only do the global unhide

thick socket
heady iris
#

In this case, it still wouldn't break

#

By default, enum values are numbered starting from zero

#
public enum BulletTypes
{
  Foo = 0,
  Bar = 1,
  Baz = 2
}
#

This is equivalent to not specifying the values.

thick socket
#
public enum BulletTypes
{
    FireBall,
ball1,
ball2
}```
#

in the past I've renamed like ball2->test

leaden ice
heady iris
#

you could avoid that by doing

#
public enum BulletTypes
{
    MeatBall = 2,
    FireBall = 0,
    IceBall = 1
}
leaden ice
#

because now FireBall and IceBall have different values than they did before

heady iris
#

note how the values aren't changing, since we gave explicit values

#

This is also incredibly aesthetically displeasing

#

I hate it

thick socket
#

gotcha

leaden ice
#

welll a normal person would add MeatBall at the end

heady iris
#

it's when you start removing old stuff that it gets bad

leaden ice
#

it's also clearly the most powerful bullet type and should have the highest value πŸ˜‰

thick socket
#
public enum BulletTypes
{
    MeatBall,
    FireBall,
    IceBall
}```
->
```cs
public enum BulletTypes
{
    MeatBall,
    FireBall2,
    IceBall
}```
in this case would "renaming" fireball ->fireball2 work?
leaden ice
#

It would work fine assuming your goal is to change all existing "fireball"s to fireball2s

thick socket
#

sweet thanks

late lion
static matrix
#

if there are scripts in a prefab, does the prefab run them?

spring creek
static matrix
#

but does the non-instantiated one run them

#

what am i saying, of course it doesn't

spring creek
#

That's why I clarified when instantiated. Before that, no.

There IS code to make things run in the editor. But without explicitly specifying, no it does not

heady iris
#

Prefabs are in a kind of weird state. IIRC they have no parent, yet activeInHierarchy is always false

static matrix
#

ok I have solved the issue: I'm just crazy

thick socket
#
public class Bullet : MonoBehaviour
{
    [SerializeField] protected float speed = 15f;
    int dmg = 3;
    string shooterTag = "";
    IObjectPool<Bullet> pool;
    public EffectTypes effectType;
    public BulletTypes bulletType;
    Rigidbody2D _rb;

    private void Start()
    {
        SceneManager.sceneLoaded += SceneChange;
        _rb = gameObject.GetComponent<Rigidbody2D>();
    }
....

if(_rb == null)
        {
            Debug.Log("rb null");
        }```
static matrix
#

while im here I'll just doublecheck

 public float Rarity;
    // Start is called before the first frame update
    void Start()
    {

        
        var rand = Random.Range(0, maxInclusive:100.1f);
        if(rand < Rarity)
        {
            Destroy(gameObject);
        }
      
    }

this works reasonably well for a structure rarity script right?

thick socket
#

why is it throwing rb=null?

heady iris
#

Show us the entire script, Hawk.

#

i realized that was ambiguous

#

:p

static matrix
#

its cool

thick socket
#

its very long so tried to just give important piece πŸ˜„

heady iris
#

i can handle it

static matrix
#

use pastebin or something like that, to avoid filling the chat

heady iris
#

There may be important context.

#

Do you instantiate the bullet and then instantly fire it?

#

Start runs before the first Update

#

which happens on the next frame

rigid island
heady iris
#

Do your work in Awake

#

Awake runs instantly after instantiation (before the method returns) as long as the component is on an active gameobject and is enabled

static matrix
thick socket
#

gotcha

#

another issue is probably I added in all the fixedupdate code

heady iris
thick socket
#

but that shouldn't run until "fire" is called

static matrix
heady iris
#

Random.Range is inclusive with floats. It's a bit weird.

#

it's maxInclusive

rigid island
static matrix
#

yeah

rigid island
#

same as 0-100

static matrix
#

I have no idea why they thought it should default to exclusive

heady iris
#

exclusive is how it works for integers

#

which is very useful for indexing a list

static matrix
#

true

heady iris
#

but again, it's always inclusive with floats

#

you just used a named parameter there

static matrix
#

ah

heady iris
#

I'd prefer it to be exclusive

#

if you use < for a chance, then 100% (1) can still fail

#

and if you use <=, then 0% (0) can succeed

static matrix
#

good idea

#

ill change it

heady iris
#

System.Random.NextSingle() is exclusive

thick socket
#
public class Bullet : MonoBehaviour
{
    [SerializeField] protected float speed = 15f;
    int dmg = 3;
    string shooterTag = "";
    IObjectPool<Bullet> pool;
    public EffectTypes effectType;
    public BulletTypes bulletType;
    Rigidbody2D _rb;
    bool fired=false;
public class WeaponAttack
{
    [SerializeField] private Rigidbody2D FireballPrefab;
    BulletTypes bulletTypes;
    MyWeaponType weaponType;
    AttackType attackType;
    Fighter fighter;
    public WeaponAttack(MyWeaponType weaponType, AttackType attackType, Fighter fighter = null)
    {
        this.weaponType = weaponType;
        this.attackType = attackType;
        this.fighter = fighter;
        if(FireballPrefab != null)
        {
            bulletTypes = FireballPrefab.GetComponent<Bullet>().bulletType;
        }
    }```
#
Debug.Log(bulletTypes);
#

this should be outputting "Curving Away" right?

heady iris
#

well, I don't know where you're actually logging that

#

if you log it after calling WeaponAttack, then probably

thick socket
#

Its being logged inside of WeaponAttack when the weapon fires

heady iris
#

not in that code you shared.

#

please don't try to trim things down for us. just share the entire script.

#

it's a lot harder to help you when you've removed (very important!) parts of the code

thick socket
#

which is called from DoAttacksAndTimer() inside of

#

which has this bullet serialized

#

inside this object

#

the top WeaponAttack code is debugging "Straight"

heady iris
#

oh, I see what you're doing

#

that's a constructor.

#

constructors are run before serialized values are restored

thick socket
#

Running debug in the window shows this

#

not sure how its not getting my Fireball Prefab at all

#

since its serialized here

#

oh...when I call

        weaponAttack = new(weaponType, attackType, enemy);
#

that wipes out my serialized prefab doesnt it

heady iris
#

that's creating an entirely new instance of your WeaponAttack class

#

it's not even wiping it out

#

the reference was never there at all

thick socket
#

dang, thanks πŸ˜„

#

Its always something dumb I do

#

I need to serialize that and pass it through constructor instead

copper rose
#

i never understand when a class can be serialze, i use it for private values to assign throw inspector, but a class serializable is when dont use update and is like an scritable object to store methods?

#

maybe this is for beginner lol

thick socket
heady iris
#

A class is serializable if it can be converted to data and recreated from data.

copper rose
#

like an scriptableobject?

heady iris
#

yes

copper rose
#

ok thanks, i never use this in my clases now i think i understand

heady iris
#

I am a little rusty on the exact terms.

#

Unity handles UnityEngine.Object-derived classes specially. They aren't serialized in-place. You just drag in a reference to the object from somewhere else

#

If you have a regular class (not derived from MonoBehaviour, ScriptableObject, etc.) that's marked as serializable, it'll get serialized in-place in the inspector

#

so you just see the values right there

copper rose
#

ok thanks so much for explain this

wraith vector
#

My player object has a sphere collider of radius 300.
How can I make that only other player object that are within that sphere will receive NetworkVariables? (for example HP of player 1 will only be sent to Player 2 when they are close)

rocky helm
#

or with (player1.position-player2.position).magnitude < 300 if you want

heady iris
#

so you're trying to implement relevancy?

wraith vector
#

but how to actually hide player 2 from player 1?

heady iris
#

(just some terms that might be useful to know)

wraith vector
#

ah, ty

heady iris
#

please do not spam

rigid island
#

cute but there is no offtopic

verbal cliff
#
    {
        if (button.GetComponent<TMP_Text>().text == DesiredWord.text)
        {
            score++;
            ScoreDisplay.text = score.ToString();
        }

        NextQuestion();

    }```

``` foreach (Button button in Options) 
        {
            button.onClick.AddListener(() => AnswerCheck(button));
        }```

causes null exception. assumably having an anonymous lambda here is bad and what causes the issues. is there another efficent way to pass button through into say TaskOnClick() or some other method?

(personal project)
turbid salmon
heady iris
#

Capturing the foreach variable should be fine.

#

You only get bitten if the variable survives from iteration to iteration

#

like capturing i in a for (int i = 0; i < whatever; ++i) loop

#

Where is the NRE coming from?

#

(don't buttons usually have the text as a child of the button?)

#

yeah, that's probably your issue

verbal cliff
#

oh yeah! i forgot to use "GetComponentInChildren" smh

heady iris
#

I would create an "Answer Button" component that holds the references for you

verbal cliff
#

thank you <3

heady iris
#

no prob

heady iris
frozen dock
#

So I need a little help. My brain does not brain.
I would like to calculate the rotation of the rigidbody on which the camera looks it needs to look to the red cross.

The blue arrow is the direction vector from the camera to the humanoid:

            Vector3 cameraToTargetDirection = unitMainManager.transform.position - mainCamera.transform.position;
            cameraToTargetDirection.y = 0;
            return cameraToTargetDirection.normalized;

The red cross is the input from the player in this case Vector2(1,0).

Would be nice if someone could help briefly.

This is the code that i got atm.

        public void RotateUnitPlayer(float rotationSpeed, Vector3 cameraLookAtDirectionVector)
        {
            if (!unitLocomotionHandler.AcceptRotationInput || unitLocomotionHandler.MovementInput.magnitude == 0)
            {
                return;
            }

            // Calculate the target rotation based on the movement input and the camera look-at direction vector
            Vector3 movementInput = new Vector3(unitLocomotionHandler.MovementInput.x, 0, unitLocomotionHandler.MovementInput.y);
            Quaternion targetRotation = Quaternion.LookRotation(Vector3.Scale(cameraLookAtDirectionVector, movementInput));

            // Smoothly interpolate between the current rotation and the target rotation
            Quaternion newRotation = Quaternion.Slerp(rigidbody.rotation, targetRotation, rotationSpeed * Time.deltaTime);
            rigidbody.MoveRotation(newRotation);
        }
heady iris
#

If you need to turn player input into a camera-relative direction, just do this

#
Vector2 playerInput = ...
Vector3 moveInput = new Vector3(playerInput.x, 0, playerInput.y);
moveInput = Camera.main.transform.TransformDirection(moveInput);
#

Now you have a direction from the perspective of the camera

#

You will probably then want to throw out the vertical component

thick socket
#

Intial speed is

_rb.velocity = transform.right * speed * 0.5f;

Is there a good way to speed up each frame in fixedupdate? running into a bit of issues because I need it to always move "transform.right"

heady iris
#
float length = moveInput.magnitude;
moveInput = Vector3.ProjectOnPlane(moveInput, Vector3.up);
moveInput = moveInput.normalized * length;
frozen dock
heady iris
#

We need to restore the original length of the vector after doing this

#

since we'll lose some magnitude

#

Then, you can just do Quaternion.LookRotation(moveInput) to get a rotation

heady iris
heady iris
#

store the current speed and add to it every fixed update

#
speed += Time.deltaTime * acceleration;
_rb.velocity = transform.right * speed;
#

Time.deltaTime and Time.fixedDeltaTime are equal while in FixedUpdate, btw

frozen dock
heady iris
#

np (:

#

I use this for all of my games now

frozen dock
#

do you got ko-fi or so?

heady iris
#

i did but i linked it to a nsfw twitter account and they got mad

#

lmao

#

thanks for offering, though :p

thick socket
heady iris
frozen dock
#

ah damn - wanted to show some grattitude

thick socket
#
 float currentSpeed = _rb.velocity.magnitude;
_rb.velocity = transform.right * currentSpeed *speedIncreaseRate * Time.deltaTime;

heady iris
#

well, it'd probably go to zero, because you're multiplied in Time.deltaTime

thick socket
#

yeah it just sat and did nothing πŸ˜„

heady iris
#

this multiplies the current speed by a speed increase rate, then divides it by the framerate

#

very wonky

#

If you want the speed to increase at a constant rate, add a constant amount to it each fixed update

thick socket
#

gotcha thanks, your way is much easier to use and configure πŸ˜„

heady iris
#

depending on whether speedIncreaseRate was below or above 50, given the default physics timestep of 0.02

thick socket
#

oh thats so weird

#

most of my projectiles hit the ground and die like they are supposed to

#

but 1 random one goes through the ground before "dying"

heady iris
#

If they're moving very quickly and the ground is very thin, they could be missing the ground entirely

thick socket
#

hmm true

#

I have a tilemap collider and composite collider for the sides and floor

#

Collision Detection is set to Continous though so wouldnt expect the speed to matter

umbral radish
#

Hey! I have a question. Are the M1 iMacs good for Game Dev?

heady iris
thick socket
#
        StartCoroutine(DestroyAfterDelay(5f));
#

is this the correct way to "stop" it if I need to?

#
StopCoroutine(DestroyAfterDelay(5f));
quartz folio
#

No

heady iris
#

You must store the Coroutine that's returned by StartCoroutine.

thick socket
#

thanks

#

could I have just done "StopAllCoroutines" instead?

quartz folio
#

That is an option, sure

leaden ice
#

if you wanted to stop all coroutines

heady iris
#

(on that MonoBehaviour)

#

StartCoroutine is a method on MonoBehaviour that takes an IEnumerator. The MonoBehaviour throws that enumerator into a big list of things it's running.

#

So passing StopCoroutine the result of DestroyAfterDelay(5f) wouldn't do anything, because it's never seen that particular enumerator

#

you can do this

var myEnumerator = DestroyAfterDelay(5f);
StartCoroutine(myEnumerator);
StopCoroutine(myEnumerator);
#

but I don't see a particular reason to do that

#

storing the Coroutine is easier

celest turtle
#

Hello! I'm trying to do this kind of thing in a 3D bomberman prototype cloning and i'm really struggling to get this right.

I've researched some ways to do it and the best result I have is using rigidbody velocity and applying it (using the target as a parameters), the problem is, using physics you can't really control the velocity of the bomb throw by time and I think it's one of crucial things to get a good game feel.

Do anyone have a suggestion on what I could do to achieve this kind of behaviour?

heady iris
#

I do not understand what you're trying to do

#

Are you talking about making the bomb fly further if you're moving in the direction you throw it?

thick socket
heady iris
#

can't really control the velocity of the bomb throw by time

#

I don't understand this

steady moat
thick socket
steady moat
thick socket
#

I dont follow πŸ˜„

#

to me that would be a rb/physics thing to do?

steady moat
#

You do not need physics as a rigidbody for the movement.

heady iris
#

I still don't know what the question actually is.

thick socket
#

If he wants to collider and push the bomb that would require physics?

thick socket
#
InvalidOperationException: Trying to release an object that has already been released to the pool.
UnityEngine.Pool.ObjectPool`1[T].Release (T element) (at <f7bcd9bfa40c4821acdda68a85850616>:0)
Bullet.OnTriggerEnter2D (UnityEngine.Collider2D collision) (at Assets/Scripts/interactable/Bullet.cs:38)

Is there a way to fix this error by checking if its already been released?

#

idk how it could happen anyway

#

but it annoys me

rigid island
thick socket
#
void OnTriggerEnter2D(Collider2D collision)
    {
        var tag = collision.transform.tag;
        if ((tag == "Fighter" || tag == "Player") && tag != shooterTag)
        {
            Fighter colFighter = collision.GetComponent<Fighter>();
            colFighter.Damage(dmg);
            //Debug.Log("Pool Release called");
            fired = false;
            StopDestroyAfterDelay();
            pool.Release(this);
        }
        else if (tag == "Wall" || tag == "Floor")
        {
            fired = false;
            StopDestroyAfterDelay();
            pool.Release(this);
        }
    }
steady moat
thick socket
#

line38 is the first pool.Release(this)

thick socket
thick socket
#

Ive just got a 2d platformer runner/gunner type game

celest turtle
thick socket
# celest turtle how?
speed += Time.deltaTime * speedIncreaseRate;
        _rb.velocity = transform.right * speed;```
#

that changed my bullets velocity

celest turtle
#

the thing is

#

i want to reach a specific target

#

a grid cell

#

if I change the velocity

#

i will miss the target

thick socket
#

I mean...once it hits the cell put the velocity to 0?

steady moat
#

You can calculate the required velocity to get to a target though.

celest turtle
#

but the movement is a parabola

simple egret
#

If you don't predict the velocity you need, you will miss, not if you change the velocity

celest turtle
#

with fixed height

#

in bomberman, the bomb always go in the same speed/height and land on the same spot (i think 4 grids away or 3)

simple egret
#

You need calculations that will apply a specific velocity so the bomb will land 1-2-3-... cells away

steady moat
# celest turtle but the movement is a parabola

For 3D:

    private void SolveForVelocity(Vector3 startPosition, Vector3 endPosition, float gravity, float angle, out Vector3 velocity)
    {
        //x = v * t

        //x = v * cos(a) * t
        //h = v * sin(a) * t + 1 / 2 * g * t ^ 2

        //t = x / (cos(a) * v)
        //h = v * sin(a) * (x / (cos(a) * v)) + 1 / 2 * g * (x / (cos(a) * v)) ^ 2
        //h = v * sin(a) * (x / (cos(a) * v)) + 1 / 2 * g * (x / (cos(a) * v)) * (x / (cos(a) * v))
        //h = v * sin(a) * (x / (cos(a) * v)) + 1 / 2 * g * x ^ 2 / (cos(a) ^ 2 * v ^ 2)
        //h = sin(a) * (x / cos(a)) + 1 / 2 * g * x ^ 2 / (cos(a) ^ 2 * v ^ 2)
        //h - sin(a) * (x / cos(a)) = 1 / 2 * g * x ^ 2 / (cos(a) ^ 2 * v ^ 2)
        //1 / 2 * g * x ^ 2 / (h - sin(a) * (x / cos(a))) = cos(a) ^ 2 * v ^ 2
        //1 / 2 * g * x ^ 2 / (h - sin(a) * (x / cos(a))) / cos(a) ^ 2 = v ^ 2

        Vector3 delta = endPosition - startPosition;

        float x = Mathf.Sqrt(delta.x * delta.x + delta.z * delta.z);
        float x2 = x * x;
        float h = delta.y;
        float g = gravity;
        float sin = Mathf.Sin(Mathf.Deg2Rad * angle);
        float sin2 = sin * sin;
        float cos = Mathf.Cos(Mathf.Deg2Rad * angle);
        float cos2 = cos * cos;

        float r = Mathf.Sqrt((0.5f * g * x2) / (h * cos2 - sin * x * cos));

        Vector2 planeDirection = new Vector3(Mathf.Cos(Mathf.Deg2Rad * angle), Mathf.Sin(Mathf.Deg2Rad * angle));
        Vector3 direction = new Vector3(delta.x, 0, delta.z).normalized * planeDirection.x + Vector3.up * planeDirection.y;
        velocity = direction * r;
    }
heady iris
#

you can also do it non-physically

#

and just make the bomb fly along a curve

steady moat
celest turtle
celest turtle
#

this is what I want to do now

#

so i can probably control the movement duration

#

and make things more on control

#

and also avoid akward behaviours

thick socket
#

now Im confused on when to use rb/physics and when not to πŸ˜„

celest turtle
#

i think you only use physics when you will need

#

in this case, i don't think its necessary because I want the thing to move from A to B in a curve

#

it doesnt really matter how

steady moat
thick socket
#

it feels weird to mix physics and non-physics objects to me

thick socket
#

gravity on enemies is nice

#

Β―_(ツ)_/Β―

steady moat
celest turtle
#

yep, but the bullets doesnt need to be physics based

#

they could be a simple translate

steady moat
#

In fact, most of the time only non important object are simulated. The rest would be Kinematic.

thick socket
#

wouldn't have like...gravity be nice?

steady moat
thick socket
heady iris
#

Rigidbodies are necessary to get collision events

#

For non-physical objects, you can use a kinematic rigidbody

thick socket
#

can you still use like rb.velocity with a kinematic rb?

#

or do you just have to use translate

heady iris
#

You have to move the rigidbody with MovePosition

#

Directly moving the transform will mess up the physics events.

hard viper
#

i think 2D is unique in kinematic RBs being able to use velocity

thick socket
#

If isKinematic is enabled, Forces, collisions or joints will not affect the rigidbody anymore

hard viper
#

but at least for 3D, kinematic RBs ignore velocity

#

velocity and forces aren’t a thing for kinematic RBs

bold pawn
hard viper
#

the whole point of a kinematic RB is: you tell it where to go and when, and nothing will stop it from going from point A to point B

thick socket
#

so I would just have to program my own collision detection, calculate the position each frame for everything to move and create my own gravity essentially

hard viper
#

yeah

thick socket
#

yikes

hard viper
#

that is kind of the point of a kinematic RB tho

steady moat
thick socket
#

If this property is set to true then the rigidbody will stop reacting to collisions and applied forces

rigid island
thick socket
#

meaning it just ignores colliders no?

#

thus I need to program my own collidiers to work?

rigid island
#

Translation is the one that goes A to B without caring anything

hard viper
#

it ignores forces from colliders

#

kinetic RBs can still hit triggers, and let other things hit them

rigid island
#

it ignores external forces but affects others but still collides with colliders

thick socket
#

but translation would let you

heady iris
#

MovePosition will model the object actually moving from point A to point B

heady iris
hard viper
#

so imagine mario trying to jump onto a platform that goes in a circle. And the platform goes in that circle come hell or high water, it does not give a fuck about what is in it’s way; it is going in that circle.
Classic case where the platform should be a kinetic RB

rigid island
thick socket
#

I guess a good question...when should you be using a Dynamic RB

hard viper
#

dynamic rigidbodies take in gravity, friction, collision forces, etc

thick socket
#

if you want things to run into each other and bounce off?

rigid island
#

when you want physics pretty much yea

thick socket
#

sounds like you should be using kinematic and just programming your own gravity

heady iris
#

a rigidbody participates in the physics simulation

thick socket
#

which I would have considered to be physics

heady iris
#

a kinematic rigidbody does not respect physics forces

hard viper
#

let’s say I want mario to chuck a penguin off a mountain, and I want that penguin to hit every rock, and deflect and slide, and have a nice parabolic arc as it falls into the void. Penguin should be a dynamic RB

heady iris
#

a non-kinematic rigidbody does respect physics forces

#

(i only do 3D, so i'm not familiar with the...static/dynamic/kinematic options in 2D?)

thick socket
hard viper
#

kinematic RBs exist to only do as they are told

heady iris
#

I guess static rigidbodies aren't expected to ever move?

hard viper
#

not hard to do. but you’d have to do it

#

and it’s a lot easier to just make it dynamic, and then it will come with friction, gravity, colliding with walls etc…

thick socket
#

well I asked up above and was told that if I just wanted to use Dynamic rb for gravity I just should turn to kinematic and make my own gravity class

thick socket
hard viper
#

you can

#

but the kinetic RB ignores forces

rigid island
hard viper
#

you need to program it to ricochet if that is what you want

#

it will register collision, but won’t get pushed back

rigid island
#

yea

jaunty sundial
#

im setting a bool fron another script true in a different script and im getting the object refrence not set to an instance of an object error does anyone know a fix

thick socket
#

so basically physics is if you want friction and "physics bouncing from hitting something or it hitting you"

hard viper
#

if you have β€œOnCollisionEnter”, it will get called, and that penguin would still keep going straight through that rock until you program it to do otherwjse

rigid island
#

that would be translation

#

not kinematic, kinematic will stop

heady iris
#

although

hard viper
heady iris
#

I dunno if you'd even call it "kinematic", since it's not a rigidbody

hard viper
#

kinematic rigidbodies do not respect forces

rigid island
heady iris
#

The character controller just has extra logic to detect that it's inside a collider and to correct its position.

#

a process called depenetration

hard viper
#

if you tell a kinematic ball to move in a straight line, it will do that, and will not care if there are any walls are in the way

#

it will go along that line

rigid island
#

if you use Moveposition / Velocity it will stop..

#

its a very common way to use kinematic rb to make a Break out Paddle

#

or Pong paddle so it collides with edges/borders

heady iris
#

(unless this is another surprise 2D/3D difference)

rigid island
# hard viper

these only referes to OnCollision events not collisions themselevs btw

heady iris
#

indeed

#

The physics system doesn't try to send collision events for literally every pair of colliders in the world

#

(that would be painful)

thick socket
rigid island
#

so its the same thing just about

hard viper
#

that kinematic yellow block is going straight through everything, because it is being told to do so

rigid island
#

theyre not even showing which method of movement they're using 🀷

hard viper
#

how do you even move a 3D kinematic rigidbody if not by MovePosition?

#

moving the transform is just doing it wrong

rigid island
heady iris
#

i can just go check lol

thick socket
lean sail
rigid island
#

guaranteed , at least with .velocity the kinematic rb will be stopped by walls

#

idk about MovePosition tbh as i dont use it

#

i just use .velocity

#

and it stops at colliders 🀷

thick socket
#

to not move through walls

rigid island
#

if you use .velocity guaranteed it wont

heady iris
#

which physics system are you talking about?

rigid island
lean sail
hard viper
#

idk. I know 2D. I know if I say β€œMovePosition to point A”, that goomba is getting to point A

heady iris
#

also, yes, a kinematic Rigidbody goes right through a wall when using MovePosiiton

#

It will push any non-kinematic rigidbodies that get in its way

hard viper
#

correct

heady iris
#

kinematic rigidbodies are not like character controllers

lean sail
heady iris
hard viper
#

in 3D

heady iris
#

they simply shove whatever they hit out of the way

hard viper
#

correct

lean sail
#

It is given velocity temporarily while moving, that's how they hit it

#

Move it*

heady iris
#

well, they certainly don't have a momentum, then :p

hard viper
#

idk last I checked, my kinematic RBs never had a velocity

#

or rather, velocity = 0

heady iris
#

If you use MovePosition to move a non-kinematic rigidbody, then it will behave as expected when banging into a very heavy object

#

the heavy object barely moves

thick socket
thick socket
hard viper
#

we don’t normally pick RB types based on performance. we pick them based on what we need done

thick socket
#

and pushes any physics?

heady iris
thick socket
#

collisions, program them yourself

#

gravity, program them yourself

hard viper
#

the point is that they do exactly what you tell them, and nothing else

heady iris
#

this is very useful for getting predictable gameplay

#

If I were making 3D bomberman, I would NOT use physics to make the bombs move

#

what if the bomb clips a collider and goes flying?

thick socket
#

I guess maybe its nice for puzzle games or things like that

hard viper
#

if I want a lift that falls down with gravity, and ignores everything else (ignores friction, any sort of pushing, etc), kinematic RBs are what you want

#

or a platform that goes in a very specific way, every time, and ignores anything else as it goes on its movement

bold pawn
#

Like gravity or a wall collider

thick socket
hard viper
#

sometimes we have really involved kinetic RB systems with character controllers. The reason to do that is to have 100% total control over every aspect of exactly how the player moves

rigid island
#

hmm turns out I had the Kinematic stop with Rb.Cast UnityChanOops

hard viper
#

because again: It only does what you tell it

thick socket
#

performance-wise how much better is kinematic vs physics

#

cause outside of a few edge cases

#

I think thats all I care about atm

bold pawn
#

I feel like you're overthinking it

hard viper
#

cheaper. because it does not care about anything in its way. But if you then supplement that with a bunch of raycasts and shit just to check collisions (to make it feel more like a dynamic RB), then there isn’t much saving

#

because you are doing what the dynamic RB was doing, but programming it yourself

thick socket
#

cause everything I have rn works fine

lean sail
thick socket
heady iris
bold pawn
#

Just pop open a new scene and experiment

heady iris
#

entirely with thrusters

#

that was my magnum opus. pain in the arse.

hard viper
#

again; we do not pick dynamic vs kinematic for performance. If you need something to bounce off walls, that calculation needs to happen. Whether you leave it to unity’s physics engine (dynamic) or code it yourself (kinematic), the computer is still doing that calculation if you want that object to bounce off that wall

thick socket
heady iris
#

the missile violently spun straight towards its target. brilliant machine.

thick socket
#

but at this point unless its for performance Its not worth me changing stuff around to "fix it"

hard viper
#

because kinematic rigidbodies ignore forces

#

kinematic rigidbodies only move how you tell them to, and ignore anything stopping them from doing what you ask

bold pawn
thick socket
#

I've messed with physics objects a lot and never had issues

#

so unless there was a performance reason to stop Im just not going to πŸ˜„

hard viper
#

if I want a ball that goes in a straight line, or in a circle, or in a parabola etc, and I want it to be unaffected by everything, that should be kinematic

bold pawn
#

It never hurts to experiment and learn.

thick socket
hard viper
#

it is way easier to program simple movement than to try to fight the physics system as it tries to push your object off course

thick socket
#

cool

hard viper
#

if I want a line, I want a line. I do not want a janky line that I need to correct to every time something gets in my way

thick socket
#

appreciate everyones insights, I definately understand it all a lot better now πŸ˜„

#

(its like 1pm and I haven't eaten today so Ima go grab food lol)

hard viper
#

back to my optimization question from yesterday, I do not understand why this code isn't super fast

#

the inner loop is normally called about 4 times, so it isn’t a massive iteration

heady iris
#

why do you believe it isn't fast?

hard viper
#

in deep profiler, this function just winds up costing several ms even for just a few dozen calls

#

and I’m baffled

heady iris
#

deep profile makes things a lot slower

#

so keep that in mind

heady iris
hard viper
#

i only took out the deep profiler because my game was lagging

#

usually both 1 or 2

#

and in future, could be bigger, like 3-4

turbid salmon
#

can anyone help me with my shop system ?

#

well first i added a coin system script called PlayerManager.numberOfCoins

#

can anyone create for me a shop system plz that has the character index and more things

heady iris
#

no, we aren't going to write code for you.

turbid salmon
#

why ?

#

i need a little help

heady iris
knotty sun
#

somewhat odd definition of 'little', creating a complete customized shop system, me thinks

heady iris
#

a shop system is an inventory system in a trenchcoat

#

so, yes, hardly ever "little"

turbid salmon
#

no it dosent need inventery it just a public void ChangeCharacter(int index) and the deselected index need to be unactive

knotty sun
#

a shop without inventory, odder and odder, what are you selling? Software or Dreams?

turbid salmon
#

oh fine wanna to see a video ?

knotty sun
#

no

heady iris
#

not really

orchid bane
#

Please don't be toxic

turbid salmon
#

i want to explain please i want to publish my game in playstore

hard viper
#

This discord is not for us to code things for you. It is to seek help

turbid salmon
#

but i like it ☺️

#

i am like gentle man ill never break rules (only do not spam idk how i can stop it)

#

let me take a look on the rules

orchid bane
#

That's the first thing you should've looked at

steady moat
hard viper
#

it's all in self

#

all the sub function calls are like Vector2.ctor etc. It's almost entirely self cost

summer helm
#

Does anybody know how I can make the trigger vibration motors on the Xbox Series X controller work in a script? There are no tutorials that I can find and the documentation about it is not helpful

thick socket
#

If I have a box like this thats "rotated" How can I determine if the X here is "above" the Y so that I need to rotate "upward" to rotate towards it

summer helm
thick socket
#

Is this how I should be doing it?

#
// Calculate the vector from the cube's position to the point you're checking
        Vector3 toPoint = pointToCheck.position - cubeTransform.position;

        // Calculate the dot product between the cube's local up vector and the toPoint vector
        float dotProduct = Vector3.Dot(toPoint.normalized, cubeTransform.up);

        // Check if the point is above the cube's local Y direction
        if (dotProduct > 0)
        {
            Debug.Log("Point is above the cube's local Y direction.");
        }
        else if (dotProduct < 0)
        {
            Debug.Log("Point is below the cube's local Y direction.");
        }
        else
        {
            Debug.Log("Point is on the same plane as the cube's local Y direction.");
        }```
#

seems way harder than I feel it should be

leaden ice
summer helm
leaden ice
turbid salmon
thick socket
turbid salmon
#

it needs a shop system right ?

summer helm
thick socket
#
Vector3 localPos = myBox.transform.InverseTransformPoint(positionOfTheRedX);
float angle = Mathf.Atan2(localPos.y, localPos.x) * Mathf.Rad2Deg;
leaden ice
#

your local up?

#

your local right?

thick socket
#

local.right

#

well...transform.right

#

I think thats the same

leaden ice
#
Vector3 dirToX = positionOfTheRedX - myBox.transform.position;
Quaternion rotationToApply = Quaternion.FromToRotation(myBox.transform.right, dirToX);
Quaternion targetRotation = myBox.transform.rotation * rotationToApply;```
#

now you have a quaternion that represents the required rotation

thick socket
#

sweet thanks

leaden ice
#

You can use this with Quaternion.RotateTowards or Quaternion.Slerp or whatever to make it smooth

#

or rather:

Quaternion targetRotation = myBox.transform.rotation * rotation;```
thick socket
leaden ice
#

yeah Quaternion.RotateTowards is good for that

thick socket
#

so I would just use it like this right? ```cs
Vector3 dirToX = positionOfTheRedX - myBox.transform.position;
Quaternion.RotateTowards(myBox.transform.right, dirToX, rotateSpeed);

leaden ice
thick socket
thick socket
#
    public Dictionary<Bullet, ObjectPool<Bullet>> bulletPools = new();
#

can I do a Dictionary like this?

#

not sure if it will see different "Bullet" prefabs as the same thing

spring creek
#

I would use something like a BulletType enum as the key

thick socket
spring creek
#

I think what you have would use INSTANCES of bullets as the key

thick socket
#

but I wanted to create prefabs with different bullet speeds

#

but yeah I think you are right, I should just set bulletspeed in code πŸ˜„

#

(for anyone wondering...yes you can do it the way I had above ^^ )

spring creek
#

You could also do strings as keys, take the enum and concat it with another enum to make a string.
Like FireBullet_Fast, FireBullet_Homing

Or something. I dunno
Edit: or maybe a tuple instead. Not sure which is less dumb haha

spring creek
lean sail
#

the prefab as a key is fine imo but the only downside is its kinda annoying for the object itself to return itself to the pool. If you try to store the prefab reference on itself, itll update to the instance of the object when instantiated

thick socket
#

I dont fully understand the second part but I do have it do this

#

pool.Release(this);

#

however other classes are the ones that call the pool to create it

lean sail
#

but thats really all

thick socket
#

ah gotcha

leaden ice
#

you just have to be very aware of which Bullet reference you're dealing with at any given time. Accurate variable names helps with this.

thick socket
#

my bullet isn't ~~rotating ~~ moving towards enemy

#

(debug shows this code is executing)

#

nvm Im dumb sorry

#

never re-set the velocity 😭

wary basin
#

Having some issues with git. Specifically, .unitypackage files. I'm trying to work on a friend's project, but we're having a lot of issues with metafiles randomly being added and removed from the repo.
Currently, they have a slurry of unitypackage.meta files that unity says need to be pushed to the repo. The problem with that - our .gitignore, and every template I've looked at, excludes any *.unitypackage files, but not *.unitypackage.meta files.
Is this intentional or not? I can't see why you'd want the meta files, but not the actual package files.

knotty sun
#

why do you have .unitypackage files in your project?

wary basin
#

Not my project so I can't speak to how it's set up, but here's a sample of the git status:

#

I did suspect that maybe the .unitypackage files aren't meant to have .meta files alongside them, but when I asked if they had ever moved their packages, they said no.

knotty sun
#

I suspect that those assets are supplying additional context in a .unitypackage file which is then unpacked into the assets folder and deleted leaving the orphan .meta file behind. you can simply add a .unitypakage.meta to your gitignore

wary basin
#

I considered that too, but the .unitypackage files are actually on this person's pc, they aren't orphaned .meta files.

knotty sun
#

I would ignore them both in that case

hard viper
#

If I have an object about to touch an area effector (or something that gives force), and it enters this region in between frames, (in between fixed update frames), does force get applied during those frames before the fixed update frame?

#

like:
Update - not in effector
Update - yes in effector
FixedUpdate - Yes in effector

#

would the object be getting pushed between the 2nd update and fixed update?

kindred hearth
#

And the force would be applied

#

Next fixed update?

thick socket
#
"Resolution.refreshRate is obsolute: use refreshRateRatio instead"
        Application.targetFrameRate = Screen.currentResolution.refreshRate;
        //Application.targetFrameRate = Screen.currentResolution.refreshRateRatio;
#
cannon convert type UnityEngine.RefreshRate to int
#

when I try the top it says obsolute, when I try bottom it throws error πŸ˜„

somber nacelle
#

access the refreshRateRatio's value property

atomic sinew
#

does anyone have any idea why float forceMagnitude = Mathf.Sqrt(2.0f * Physics2D.gravity.y * _bounce); returns NaN?
_bounce is 4 here and gravity is set to -47, so nothing weird going on here. i tried setting physics to -9.81, but same problem

#

*gravity, not physics

somber nacelle
#

the square root of a negative number is NaN

thick socket
atomic sinew
thick socket
#

thanks πŸ™‚

#

leave it to Unity to make something that works nicely have to have a cast now

#

very fun

sly crag
#

hey guys, I need to make a single sctipt for all weapens and make the children inherit it, but when I use OnTriggerEnter, and I get triggerd with the child object it doesn't detect, the funcion is public and the children has a collider that is triggerd.

spring creek
sly crag
spring creek
rain minnow
spring creek
spring creek
sly crag
#

this might clear things

#

Weapons Script:

public class Weapons : MonoBehaviour
{
public void OnTriggerEnter(Collider other)
{
print("test");
}
}

Pistol Script:

public class Pistol : Weapons
{
}

spring creek
sly crag
jaunty sundial
#

ok im changing the layer of a prefab halfway through the game to ground however when the game ends the prefab doesnt go back to its original layer in the editor

#

why is that

sharp rose
#

hello, I am currently trying to activate the children of my parent object through a script in the parent object. I figured out how to reference a variable from an entirely different script but now I am struggling with figuring out how to activate each of the children based on the value of the variable from the other script. How do I go about this?

spring creek
spring creek
sharp rose
#

The value is from an entirely different object and script