#archived-code-general

1 messages · Page 34 of 1

faint relic
#

can anyone help im trying to make a weeping angels script and i cant seem to get it to work

hard sparrow
#

Coding Riddle: Guess what hrt stands for.

simple echo
#

i want to make a score system in my 2d game. so if the player collects power-ups their score increases and if the player collides with enemies their score decreases. i want to display their current and high score on a leade board. does anyone know how i should go about starting to implement the score system? is there a database of any sort? ive heard about process data base

leaden ice
#

have your objects call out to the singleton when necessary to increase/decrease the score

simple egret
hard sparrow
#

Pft, no one's guessing. No fun. Answer = HexRuleTile

simple egret
#

And those cases are not even in binary, weird

#

Maybe that's just how Unity handles it anyway

hard sparrow
#

The position of the int maps to directions. That way you can reverse the int and check for mirrored positions

simple egret
#

Position of the int? Reverse?

#

You mean where the ones are in the number?

hard sparrow
#

You check to see if the bitcode is here, if not:

#

(I think it's kind of clever)

#

That way you need half as many cases and half as many sprites

leaden ice
hard sparrow
#

Nothing in the code actually is reading binary

leaden ice
#

likewise you can make the enum use those bit patterns directly and then you would't need this switch at all.

hard sparrow
#

it's just checking to see if the northeast tile matches, if so add 1 to the bitcode

hard sparrow
#

If you tell me my clever solution sucks, I will be both grateful and salty

simple egret
#

To be honest it's not really clear what's happening here

leaden ice
# hard sparrow What do you mean?
public enum hrt {
  alone = 0,
  NE = 10000,
  E = 01000,
  ... etc, matching what you have in that switch
}```
Then instead of that big switch you literally can just do:
```cs
return (hrt)bitcode;```
hard sparrow
#

Well the hrt.X are sprites. I assume you still need to do some kind of switch case to get the correct sprite

leaden ice
#

Oh I assumed it was an enum

#

well you could use a dictionary, but whatev

hard sparrow
#

Hex tiles can be a pain in the arse, lol

#

Oh you're right, a dictionary would be more performant I suppose

#

Yeah I'll do that

leaden ice
#

eh

#

it'll probably be the same

#

the compiler will create a jump table for it

hard sparrow
#

Well then I'll make it a dictionary just to not look like a noob, lol

simple echo
hard sparrow
#

There are a lot of tutorials on making singleton

#

It's pretty simple

#

It just means you can access it anywhere without reference

simple echo
#

ahh okay! i want to use something that is not unity's built in. so was intially thinking of Postgress

leaden ice
#

you're jumping ahead to the leaderboard part
you need to get scorekeeping working in the first place first, just in the local game

brazen junco
# simple echo ahh okay! i want to use something that is not unity's built in. so was intially ...

Depending on what you mean, Postgres might not be a good option here. Postgres is a DBMS that would run as a separate process. This is no problem on the server side where you have everything under control, but on the users device, it would really be a hassle to make sure that Postgres is installed, and that it runs, and to restart it if it gets stopped, and to stop it when not required anymore, etc.
If it's really just about a highscore on the players device, something like PlayerPrefs would be an option (even though they have downsides), or saving into a file in the filesystem (a bit more elaborate, but more flexible). A DBMS would be rather overkill, but if really necessary, I'd go for an embedded database like SQLite.
For online scores, this is a different matter, but the game shouldn't directly write into the database anyway.

steep scarab
#

Hey guys, I'm currently trying to get the horizontal angle between two points in degrees but I'm having some trouble. Currently "angB" is returning me numbers between 0 and 1. I understand this is because vector3.normalized just brings x, y and z to a magnitude of 1, however after converting newDir to a quaternion and setting angB to that quaternion.eulerAngles.y, I am STILL getting values between 0 and 1. Does anyone know of a quick way to get this value in degrees? I know this question is kinda poorly worded but I'm trying my best.

        Vector3 newDir = (testFront.position - testBack.position).normalized;
        float angB = newDir.y;
        Debug.Log("b: " + angB);

I was thinking of using trigonometry to find the angle but that seems somewhat arbitrary in future cases, just wondering if there's a built in method for finding newdirs y eulerAngle. (and also does anyone know why converting newDir to a quaternion and setting angB to that quaternion.eulerAngles.y doesn't work for some reason and instead returns values between 0 and 1?)

Also, sorry for the double question but I didn't get any response in #💻┃code-beginner

leaden ice
#

What is a "horizontal angle"?

steep scarab
#

as in

#

imagine a transform facing another point in space

#

the y euler angle

#

of that transform

leaden ice
leaden ice
#

You want this:

Vector3 dir = testFront.position - testBack.position;
float angle = Vector3.SignedAngle(Vector3.forward, dir, Vector3.up);```
orchid surge
#

I'm looking for opinions on a couple of scriptable object patterns. I am on the fence about using scriptable objects to share variables or keep track of sets of objects at runtime because I don't like the feeling of using the inspector to assign variables like "IsPausingAllowed" to the PauseController and GameLoopController. It doesn't seem like this meaningfully decouples the systems at the cost of making more room for error. But it still seems like a solid alternative to direct references between the classes or raising a game-wide "Action<bool> IsPausingAllowedChanged" in the GameLoopController. Am I overthinking this or is there an interesting question in here?

#

I am definitely overthinking this, but there still might be a good question here.

hollow stone
#

I don't understand what the purpose of having a SO is in your case?

orchid surge
#

To share the variable and respond when it changes. But the SO definitely doesn't do anything that can't be done otherwise.

#

I think I got what I wanted from this exchange lol. SO doesn't add anything and I listed the problem. I needed to follow my heart and just do this the normal way like I had it before.

hollow stone
orchid surge
#

I typed out a paragraph about SOs as runtime sets and kinda answered my own question. I probably want to drop the SO part cause I don't like the manual half and I'm working solo so there are no designers to account for. But I need to think about what my options are cause I don't really want to make a singleton service to access a list of player controlled characters.

hollow stone
#

Personally I don't really like the idea of disconnecting the variable to such extent that it complicates following the code where it reads and writes to it (having generic float SO). And it can also lead to bad behavior of having all your variables as SOs in project. Instead I would create a data/model that decouples different systems that wants to read from it.

steep magnet
#

Whats the best way to go about putting an object in here that is in a different scene?

somber nacelle
#

you can't. you'd have to add the listener at runtime when both objects exist at the same time

brazen junco
steep magnet
#

i have an object on the player that updates their hydration. i want to call the function that sets it to max when the player picks up the water bottle

#

i figured i could probably just create a gameobj to put there that the hydration script checks if i wasnt able to do it the prior way

worthy turtle
#

Hi all , Im using Unity Render Streaming package and getting this issue when I build webGL , I'm sure the problem has something to do with assembly references as earlier had missing assembly errors in the console fixed by adding an assbly reference in the script folder. Now getting no build errors but this in web console. Any ideas?
A scripted object (probably Unity.RenderStreaming.RenderStreaming?) has a different serialization layout when loading. (Read 32 bytes but expected 184 bytes)
Did you #ifdef UNITY_EDITOR a section of your serialized properties in any of your scripts?

orchid surge
swift falcon
#

FindObjectOfType<>() - does that search all opened scenes?

#

or just the main one (where the calling monobehaviour is)?

leaden ice
leaden ice
solemn raven
#

hi
Im building my own UI and pagination
I wanna round up small floats like 6.1 to 7 ( 7 pages )
how do I do that ?

solemn raven
swift falcon
#

why Linq Where returns me a bool array instead of GO array?

#

i think its different Where, not the one in LINQ

lucid valley
#

yeah double check as it shouldnt do that

swift falcon
#

i see

#

so it doesnt know which Where to use

#

is there a way to specify?

lucid valley
#

uh, i guess you could call the static method itself

brazen junco
lucid valley
#

Linq.Where(GameObject.Find...(genAroundTag), tt => ...).ToArray(); ... where the rest of the code is as i didnt want to type it out

lucid valley
wide mural
#

What would be the best way to display an action on object? I already have a raycast to detect what the player can do with near object (pick up for example) but how would i do to display an icon?

Like on this game

#

(with a third player camera)

polar marten
fresh yarrow
#

can y'all help me with this script (i've done walking part, now i need help with jumping)

polar marten
#

that toggles

#

into the "active" shape when your pointer is over an object of interest

#

the position of this ugui object would track the 3d object

#

does that make sense?

fresh yarrow
#

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{ _controller = GetComponent <CharacterController>()
private CharacterController _controller;
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
Vector3 direction = new Vector3(horizontalInput, 0, verticalInput);
_controller.Move(direction);
// This is a reference to the Rigidbody component called "rb"
public Rigidbody rb;

public float forwardForce = 000f;    // Variable that determines the forward force
public float sidewaysForce = 00f;  // Variable that determines the sideways force

// We marked this as "Fixed"Update because we
// are using it to mess with physics.
void FixedUpdate()
{
    // Add a forward force
    rb.AddForce(0, 0, forwardForce * Time.deltaTime);
    
    if (Input.GetKey("d"))    // If the player is pressing the "d" key
    {
        // Add a force to the right
        rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0);
    }

    if (Input.GetKey("a"))  // If the player is pressing the "a" key
    {
        // Add a force to the left
        rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0);
    }
}

}

#

can y'all help me with jumping?

wide mural
polar marten
coral kestrel
#

Hello. Just to preface this I am pretty new to coding so my problem is 100% just a result of my lack of knowledge. I'm making an adventure game and I'm using the Inventory scripts from one of Brackeys' RPG tutorials, but I'm also using a save/load system from another tutorial and the two are not cooperating.
My issue is that everything works as intended so long as I don't switch to another save or exit the scene, at which point everything goes haywire and the result is what can be seen in the images - the items in the inventory are carried on to the other save, even though they've not yet been collected, and the pickup is active. Whenever I click on the pickup the whole inventory gets filled up with copies of the item.
Here's a link to the scripts, which I think are related to my issue: https://paste.myst.rs/luwxb9w4
I've been hitting my head against the keyboard for some time now trying to figure out a solution so any and all help is welcome!

cyan hill
#

i'm wanting to connect to an sqlite db from a Unity script. i've got the DB and the code written, but I can't get the plugin to work. I've copied several versions of the Mono.Data.Sqlite3.dll file from various folders in the Unity editor folder to my Assets/Plugins/ folder, but I get an error when actually running the code each time. It's been three different errors. I've tried to pull from the unityjit-win32 folder, 4.0 folder, and one more. any clear instructions on how i can get this to work properly? thanks!

rain minnow
cosmic rain
cosmic rain
polar marten
#

there ar efree ones for sqlite

#

there is probably also a github package

cosmic rain
cyan hill
#

Sorry, had to pop out. Will ask again tomorrow when I'm at the PC again for enough time. Sorry about that.

wide mural
#

So just trying to display the position of a 3D objects into my canvas ui with WorldToScreenPoint.

But the position doesn't seem to be the same. Thought it might be related to resolution/scale of Canvas so I did this (image)
But that does not work.

Is my code wrong? could it be related to using cinemachine?

cosmic rain
wide mural
#

Scale it back to the current resolution?

#

If its different

cosmic rain
#

It should map to your screen pos correctly without any additional math manipulations.

wide mural
#

Well it doesn't, would it be due to cinemachine?

#

I know I have the right 3d world pos since I can literally see the raycast

cosmic rain
#

I'm not sure. What do you get from just WorldToScreenPoint?

wide mural
#

U mean what value for screenPoint?

cosmic rain
#

Yeah. Well, visually, how does it correspond to the world pos?

wide mural
#

1st image is in game, i used simple unity icon for now xd
2nd image is the raycast in scene

#

so the point is at the branch

#

These are my canvas settings

#

this is the position i get

cosmic rain
#

Take a screenshot of the scene view with the canvas visible and the image selected.

wide mural
#

you mean like this?

cosmic rain
#

Yeah. So, I might be wrong, but since you set the anchored position and the image is anchored to the center of the screen, you get in the wrong position.

#

Try setting transform.position instead.

wide mural
#

thank u that worked

#

I guess that makes sense, stupid mistake

modern creek
#

I have a particle system, a starfield - with particles that have long lifetimes and no movement. Can I change the values of their speed while they exist somehow? It seems as if I change the main module parameters just fine but it only applies to new particles.

#
            var spsMain = StoppedParticleSystem.particles[0].main;
            MinMaxCurve spsMinMaxCurve = spsMain.startSpeed;
            spsMinMaxCurve.constantMin = 100f;
            spsMinMaxCurve.constantMax = 200f;
            spsMain.startSpeed = spsMinMaxCurve; // no effect to particles already emitted
leaden ice
modern creek
#

Hm.. I thought I checked that module.. I'll look again

#

Nope! this should be what I need.. just ramp up the speed modifier of that module, I think

leaden ice
#

You're looking at start speed only

modern creek
#

I'm not quite sure if these modules are playing nice with the UIParticle library though

#

I mean, "nope" as in "nope I didn't check here earlier"

leaden ice
#

Start speed is just that - the speed when the particles spawn

modern creek
#

looks like the VelocityOverTime.SpeedModifier (whatever the actual ones are claled) is what I need - i'll just tween that up and it should work fine

#

thx

shrewd obsidian
#

Is browser game performance significantly affected by the PC running the browser? I always assumed they weren't but the browser build of my game runs fine while the mobile build runs terribly. UnityChanThink

leaden ice
#

WebGL is no exception

modern creek
#

Have the stars accelerating nicely with that, thanks @leaden ice.

tepid juniper
#

Dear friends, could anyone help me with namespaces?
So I have a asset which have namespace, have it own folder and etc. In different folder I created different script with namespace. I would like to access classes that are in my own namespaces. However when I try to use that namespace visual studio states it doesnt exists. So I assume as it is because namespace fil is not in the same folder. What should I do?

wary dirge
#

I am using trying to place an object with user touch using raycastmanager to get the position and rotation but after placing the object using instantiate the model is shaking and sometimes floating. Can anybody help me with this

#

I don’t want the model to move it should be at that place until destroyed

leaden ice
#

unless you are simply not including the appropriate using directive.

#

The problem is your asset likely has an assembly definition file

tepid juniper
#

I am including using NameSpace. In all other scripts it works, but not in asset I mentioned.

leaden ice
#

in general though you shouldn't be modifying asset code unless you have a really good reason

tepid juniper
#

well asset lets you create custom JS code to handle specific streaming service, but I cant pass parameters to C#, as it requires more data than others. So that is pretty reasonable reason to edit asset code. Trust, I wish I shouldn't.

sterile tendon
#

how do I run python scripts in c#?

#

all it does is return a string

leaden ice
tepid juniper
# leaden ice > I cant pass parameters to C# What do you mean by this? What parameters do you ...

First of all it is Webgl, so half of code works on C# and other on JS. it is AvPro asset meant for showing videos. Normally it requires only path, as HLS streams don't need anything else. But WebRTC stream needs Login information. I have scriptable object, that have all data needed, and Javascript which works when data is hardcoded. But I cannot pass the scriptable object to the AvPro monobehavior. References don't work as it cant see that Scriptable object class. I also cannot use FindObject and then get data from singletons, as they are also invisible for this AvPro monobehavior.

So only reason I can see, that either the AvPro monobehaviour is in folder Runtime, and somehow it puts it in other order of compiling or idk....

But anyways I am running out of ideas, only idea left is create custom script that will pass string values to that AVpro monobehavior at the runtime on awake. Anyways this hacky solution is annoying.

Other solution pass Javascript data from different scripts, but that not ensures of JS compiling order and might not see correct data.... halp.....

leaden ice
#

I have scriptable object, that have all data needed and Javascript which works when data is hardcoded

You can pass data from the C# side to the JavaScript side.

tepid juniper
leaden ice
#

I'm not sure I understand what you mean

#

why would there be a question of execution order

#

are you not creating/configuring these objects/components in your own code?

#

Can't you just:

  1. pass data to JS
  2. initialize the AvVideoPro stuff
#

in that order

tepid juniper
#

isnt JS compiled on build with all classes and stuff?

leaden ice
#

Well first JS is not compiled at all, but second what does when it is compiled have to do with anything?

tepid juniper
#

what do you mean it is not compiled? JS is created from all unity scripts in your project and placed in one big ass JS file. And JS does care about order.

leaden ice
#

regardless

#

you control when the code executes, no?

#

and "placing js in a file" is not the same as compiling but I digress

tepid juniper
#

I control when code is executed. I can make sure my script runs before asset script. But does Unity tracks then when it is CREATING the JS file? As on browser you will just get error that your parameters are null or dont exist.

Regardless, I chose to go with most retarted way, to pass bunch of string on awake to that asset, and use that data when needed. But still I wish I could be able to add references to script from other namespaces 😭

leaden ice
#

again it's not a question of namespaces

#

it's a question of assemblies

#

You could do it if you set up your assembly definitions. But it's much more of a pain than is worth this issue. Better not to modify libraries if you can avoid it

thick sail
#

Hey guys, new to Unity (not to software development), I'm having some trouble finding canonical methods to do TDD in Unity, could someone point me to any useful resources? Thanks!

leaden ice
thick sail
#

Awesome, any books or articles to go along with it? I'm interested in snapshot testing, replays, etc as well

surreal phoenix
#

what do i have to do to make my scriptable pipeline visible in the project's pipeline picker?

spring basin
#

hello I need with a hole physics, I painted a hole in a terrain and would like the ball to fall into the hole, if it passes through it

#

but there's a weird interaction when only the partial ball is on top of the hole space

#

the sphere cuts through the terrain texture instead of falling into the whole due to its mass (something like a side spin because of the weight of the sphere inside the hole)

#

I feel i made a mistake in how I push the ball forward?

#

ballBody.AddForceAtPosition(new Vector3(0f, 0f , explosiveForce), Vector3.forward, ForceMode.Impulse);

leaden ice
# spring basin

you sure you want to use Terrain here instead of just like a ProBuilder mesh?

spring basin
#

😮

#

ProBuilder mesh?

#

i wasnt aware of it

#

will check it out

vague slate
#

Is there any way to view scene including all hidden objects?
I uninstalled URP and now it constantly throws warning about missing scripts (meaning there are some garbage objects hidden in a scene)

leaden ice
spring basin
#

whats the variable

#

name

#

i was trying out the different

#

ah

#

i shouldnt use Vector3.forward?

leaden ice
#

Why are you not just using normal AddForce is what I mean

leaden ice
spring basin
#

okay will try that once and write back

#

AddForce has the same interaction

leaden ice
#

yeah the interaction has nothing to do with how you're adding force

#

I was just commenting on it being very weird

spring basin
#

oh okay 😛

#

how do I configure my setup to behave on the weight?

#

of the sphere

toxic fog
#

I wanna look something up but I don't know what it's called
it's like, a click map? I want the cursor to do different things when clicking on different sections of an image/screen. the areas would likely be amorphous shapes.
like, if I wanted to have a "pet the dog" system and based on which spot of the head you pet it'd interact in different ways.

#

it looks like it could be done with raycasting, but can raycasting distinguish more than one color at once?

#

Also, could raycasting pick up the color of an image that's invisible to the player somehow? So I can hide the interaction map, and it'd just look like you're petting a dog, and not petting a dog-shaped blob red, blue, green, etc

main shuttle
#

Technically you could also hide the value in the alpha channel of your pixels. Then you wont need the second image, but that's just an idea I though of now.

toxic fog
pastel patio
#

I'm making a 3d hack&slash action game, but I have trouble with weapons ignoring collisions when low frame rate/swinging extremely fast, anyone have experience with this issue please? It's bothered me across a lot of attempts already

#

And... Also, weapons could sometimes be swinging slowly, which is why I can't even use a custom mesh collider, as the weapon would hit target before it visually did..

main shuttle
toxic fog
#

Yeah, all I needed to know was that it was possible! I'm excited now c:

elder temple
#

How do I calculate direction of enemy object from player, but only 4 basic direction( east, west, north, south) ??

west lotus
#

I would calculate the direction vector from player to enemy. Then do a Dot product with the 4 cardinal directions, closest result to 1 is your answer

swift falcon
#

does it matter what scenes are open in unity when u build?

#

or only build order in build settings?

rigid island
keen eagle
#

Hi I have a image with opacity of 25% but when I use the image as background in unity the opacity doesn't take effect

main shuttle
deep fable
#

If I use Instantiate(myScriptableObject) will I receive a shallow copy of the scriptable object?

main shuttle
lucid valley
#

^

deep fable
#

If I have a variable which is of type MyClass inside the SO, will it also clone that variable? (making it point to another heap allocation)

lucid valley
#

if you just want the same one then don't instantiate it just use myScriptableObject

deep fable
#

It's not the SO itself, it's the variables inside it that I want to clone

lucid valley
#

pretty sure it's going to deep copy and do new allocations

main shuttle
#

Just like the normal behaviour.

lucid valley
#

if you don't want that then you'll need to make your own cloning function for that SO

wicked scroll
swift falcon
#

https://gdl.space/ojucitucoq.cpp The scene is called once I press play and runs as intended the first time, when the scene is called the second time during the same run, the text doesn't iterate through and gets stuck on the first text, please someone help

main shuttle
lucid valley
#

and then set the references to the fields again

deep fable
#

Ok thanks to everyone

deep fable
#

Why UnityEngine.LayerMask is not marked serializable? It's an int..

rain minnow
main shuttle
hexed pecan
#

uint could work too

lucid valley
sage pike
#

Hi, how can i set visual studio such that when i click on 'F1' on my keyboard it will open unity document? right now it's not working...help please

zenith dirge
#

How does FlowMap UVs work?
I know, on the X (U) axis, 0 is left, 0.5 is middle (stopped) and 1 is right
On the Y (V) axis, 0 is down, 0.5 is middle (stopped) and 1 is up
But I can't seem to find the correct combination to make a curved spreading flow on this mesh
I want the flow to go from the larger edge to the smaller and spread out in a circular pattern, like at the end of a river meeting into an ocean
How can I do this?

rustic ember
#

What does the flag mean?

lucid valley
rustic ember
rustic ember
idle meteor
#

Hello, now I am developing a ui system. But I ran into a problem. I close the UI window opened in my update method under UI Manager when the escape key is pressed. But on the other hand, I am trying to open the pause menu in my update method under Game Manager. The two conflict and the pause menu closes before it even opens. How can I prevent this?

#

Additionally, do you know of a good UI management system? Or a tutorial on how to do it?

leaden ice
lusty dragon
#

Hey everyone, I am trying to move a go but its child containing the sprite does not move with it. any idea?

idle meteor
leaden ice
#

A similar path

#

Use a bool variable

idle meteor
#

OK, I'll try. Thank you for your support.

lusty dragon
#

does the following move the objects children as well?

transform.position = pathCreator.path.GetPointAtDistance(distanceTravelled, endOfPathInstruction);
leaden ice
#

for example dynamic Rigidbodies will overwrite any such movement

lusty dragon
# leaden ice moving a parent always moves the children unless another script or component cou...
public class PathFollower : MonoBehaviour
    {
        public PathCreator pathCreator;
        public EndOfPathInstruction endOfPathInstruction;
        public float stoptimer;
        public float speed;
        float distanceTravelled;
        

        void Start() {
            stoptimer = 0;
            if (pathCreator != null)
            {
                // Subscribed to the pathUpdated event so that we're notified if the path changes during the game
                pathCreator.pathUpdated += OnPathChanged;
            }
           
        }

        void Update()
        {
            if (pathCreator != null)
            {
                distanceTravelled += speed * Time.deltaTime;
                transform.position = pathCreator.path.GetPointAtDistance(distanceTravelled, endOfPathInstruction);
                //transform.rotation = pathCreator.path.GetRotationAtDistance(distanceTravelled, endOfPathInstruction);
            }
            if (stoptimer > 1000)
            {
                speed = 0;
               // stoptimer = 0;
            }
            if (stoptimer < 500) speed = 0.2f;
            if (stoptimer > 1200) stoptimer = 0;   
        }

        // If the path changes during the game, update the distance travelled so that the follower's position on the new path
        // is as close as possible to its position on the old path
        void OnPathChanged() {
            distanceTravelled = pathCreator.path.GetClosestDistanceAlongPath(transform.position);
        }
leaden ice
#

What am I looking at here?

deep fable
#

How can I find all the types that implement a specific interface? Because I am doing this:
Assembly.GetExecutingAssembly().GetTypes().Where(type => type.IsAssignableFrom(typeof(IEffectConfigData)) && !type.IsInterface).ToArray(); but it returns me nothing (but if I log all the types in Assembly.GetExecutingAssembly().GetTypes() I see the types that implement the IEffectConfigData interface)

leaden ice
#

Where(type => typeof(IEffectConfigData).IsAssignableFrom(type) && !type.IsInterface)

deep fable
#

Oh thanks!

#

Is there a way to call a static function after script compilation? I remember seeing an attribute from a video, but I don't remember its name

#

Because [DidReloadScripts] doesn't seem to work (or at least on a scriptable object)

#

Oh I found it (it's [InitializeOnLoadMethod])

lusty dragon
hexed pecan
leaden ice
woeful leaf
#

(Also !cs)

tawny elkBOT
#

You can format your multiline code block with C# highlighting! Just add cs to the start of it. Highlighting example below!

class Fluffs : FluffyCat
{
    public void PetCat ()
    {
        Debug.Log ("Petting Cat.")
    }
}
lusty dragon
hexed pecan
#

Lol all good

pallid warren
#

I need help. I have a script that instantatiates some prefabs. I ctrl+C ctrl+V one prefab and change its name. My script can't find that prefab to instantiate but all other are ok. What is going on?

leaden ice
somber nacelle
#

also you can pass the component reference to Instantiate and it will clone the entire object and return a reference to the instance of the component so you wouldn't need to do Instantiate(frameRess.gameObject).GetComponent<T>(); you could just do Instantiate(frameRess);

woeful leaf
#

Why am I getting this? I have no errors

#

Restarting VS fixes it, whack

deep fable
#

Can I serialize a variable (of type MyClass) like if all its fields were actually of the class containing it? Basically "flattening" the variable in the inspector

lucid valley
lucid valley
deep fable
#

Yeah but there is a dropdown menu if I do like that (I want to remove the "drop down" menu)

lucid valley
#

i thought you wanted that?

#

oh, so you want the opposite

#

uh, maybe with a custom inspector

polar marten
#

what are you trying to do?

#

what is this all for?

deep fable
#

I am creating a card game and I have an abstract class Effect and multiple classes inheriting it. Each effect has some config data (like duration, radius...) and I have made an Explosive struct that is inside the Mine and Bomb effects (because they share a lot of things). Now I would prefer to not see Explosive inside the inspector when editing the fields inside the Explosive variable

(The [DidReloadScripts] thing was to automatically instantiate Card scriptable objects for each effect I have in the project, but I've solved it)

#

It's like removing that red circled thing

soft mica
#

Are there any libraries or assets out there which allow one to add new bones to an existing armature at runtime?

I'm looking for something simple where I can specify a radius of influence and a falloff for the bone. It probably needs to leave the existing bone weights intact as well. I'd like to be able to drop an empty game object in a location, with this component attached to it, set a few values on the component, like the radius, falloff type, and mesh to deform, and have that game object act like the bone, moving the vertices with it when it moves.

cyan hill
#

i've been trying to connect to a sqlite3 database from a script. i have the code written up, which should be ok. the problem is that I need to load Mono.Data.Sqlite for it to work, but it won't load. checking online, it said i needed to copy the .dll from the editor folder, so I grabbed it from \Editor\Data\MonoBleedingEdge\lib\mono\unityjit-win32 (i've tried a few other locations, too). the error i still get is:

DllNotFoundException: sqlite3 assembly:<unknown assembly> type:<unknown type> member:(null)
Mono.Data.Sqlite.UnsafeNativeMethods..cctor () (at <113d9163ee3244aba7dbd348e28f7f70>:0)
Rethrow as TypeInitializationException: The type initializer for 'Mono.Data.Sqlite.UnsafeNativeMethods' threw an exception.
Mono.Data.Sqlite.SQLite3.Open (System.String strFilename, Mono.Data.Sqlite.SQLiteOpenFlagsEnum flags, System.Int32 maxPoolSize, System.Boolean usePool) (at <113d9163ee3244aba7dbd348e28f7f70>:0)
Mono.Data.Sqlite.SqliteConnection.Open () (at <113d9163ee3244aba7dbd348e28f7f70>:0)

i've tried moving it to different nested folders, the base folder, Plugins/x64/libs/, no dice.

#

basic code, as well:

        IDbConnection dbConnection;
        string connectionString = "URI=file:" + Application.dataPath + "/main.db";

        dbConnection = new SqliteConnection(connectionString);
        dbConnection.Open();

        IDbCommand dbCommand = dbConnection.CreateCommand();
        dbCommand.CommandText = "SELECT * FROM abilities";
        IDataReader reader = dbCommand.ExecuteReader();
cinder basin
#

hey guys

#

does anyone know if it's possible to do gpu instancing for animations while also keeping animation layers?

polar marten
#

this isn't sounding like a coding question yet. what is your objective?

polar marten
#

did you try using a sqlite asset from the asset store?

#

the error message is telling you you don't know how to put sqlite into unity

#

copy the .dll from the editor folder
this doesn't sound right

cinder basin
#

there's a technique for gpu instancing animations, but all I've found so far was batching/creating shaders, but none of the methods are allowing for animation layers

polar marten
cinder basin
#

yes, pretty much

#

tbh I might have even a 100, but even that number of skinned meshes causes fps to drop drastically

#

so I'm looking for a way to optimize it as much as possible without sacrificing features

polar marten
#

hmm

#

i don't know anything about this stuff sorry

#

i've seen cool demos with DOTS

cyan hill
cyan hill
cyan hill
#

not trying to be combative, just genuinely curious. it seems like using sql in unity really shouldn't be that hard

#

thanks!

floral needle
#

Hey guys, I'm making a grenade that creates sort of a "force field" that slows down time inside it. Is there any way of limiting a Time.timeScale change to a particular location, or do I have to make a different multiplier for the things that I want to slow down?

floral needle
#

Figured, thanks

prime sinew
#

Easiest way is probably to use a public static float and multiply that with the things that need to be modified

woeful leaf
#

I've this code and it does run the print, but it doesn't play the audio but I don't get any errors, what could be the problem?

    private void OnPressed()
    {
        print("I should be playing");
        sound[1].Play();
    }
floral needle
prime sinew
woeful leaf
#

I think I already know the culprit though

prime sinew
#

Idk then. Try playoneshot

#

Okay cool

woeful leaf
#

I'll

woeful leaf
steady moat
# cinder basin so I'm looking for a way to optimize it as much as possible without sacrificing ...

The big issue with those type of project is that SkinnedMeshRenderer cannot be batch natively and are done on the CPU which result of high CPU usage and high draw call number. Fortunately, there is some people that worked on a GPU Base Skinned Mesh. https://blog.unity.com/technology/animation-instancing-instancing-for-skinnedmeshrenderer, https://www.youtube.com/watch?v=_GGVlzAcWgA&ab_channel=Dr.ShahinRostami

Note: It is not a magical solution, it shift the load from the CPU to the GPU and you lose a lot of functionality.

woeful leaf
somber nacelle
#

yes you would need to disable all renderers on the object for it to be invisible. of course you'd probably want to disable any colliders as well

#

or just make the audio source a separate object that doesn't get disabled

woeful leaf
#

I'd probably have to restructure a lot of code if I want to do it that way Thonk

#

Would it be bad to just move out of the screen?

somber nacelle
woeful leaf
#

There's no main controller

somber nacelle
#

you don't need any sort of "main controller" to be able to have the audio source separate from the renderer and stuff

woeful leaf
#

Well they'd have to reference to an object besides itself

somber nacelle
#

so?

woeful leaf
#

Which that'd be a "main controller" of sorts, since all point towards it

somber nacelle
#

no . . . it would simply be a reference

rigid island
#

no it's not

swift falcon
#

how to get a reference to an object in different scenne?

#

.Find and .FindObjectOfType and scene.GetRootGameObjects doesnt work

#

maybe Tag wouldnt work but i dont wanna add a tag just for that ...

subtle herald
#

grab the scene first

#

SceneManager.GetSceneByName()

#

then access the object in it

#

with GameObject.Find()

#

keep in mind, this target scene has to be in your build settings to be accessible at runtime

swift falcon
#

i see, it wasnt loaded yet

#

it needs a delay

subtle herald
leaden ice
#

and yes the scene needs to have been loaded first naturally

#

These methods are quite slow though

#

using a singleton would be faster

regal marsh
#

do audio sources in unity automatically use surround sound? Like if I code an enemy to have its own audio source, will the audio play relative to where the listener is?

somber nacelle
simple egret
#

Yes, as long as the source has 3D sound enabled (not a code issue)

regal marsh
#

alright i'm asking in code because i have a problem

#

i have an sfxmanager class i made myself

#

and it has functionalities that I can just call from anywhere. i've got an IsPlaying() method that used an audio source attached to the same object as the sfx manager, but if I want to do surround sound, I need to pass in different sources. I tested this and it works, but how can I check and see if a certain sound effect is playing from only one audio source at a time?

#

i'll send the code real quick

polar marten
regal marsh
#

i have zombie enemies that i don't want to be making the same sounds all at once. unless i can do surround sound based on a certain gameobject with the audio source attached to the manager

simple egret
#

Why not attach a source to the zombie?

regal marsh
#

i did

#

and i am passing it in

#

that's my problem though

polar marten
#

i think you can limit the number of sounds

#

that are playing simultaneously

regal marsh
#

of a specific type?

polar marten
#

using the existing unity audio tools

regal marsh
#

or specific file?

#

if not that's fine

polar marten
#

i am confident you can do it however you want

#

but i odn't know much about unity audio

#

you would have to read the docs

regal marsh
#

or if that's even what i'd want to do

#

oh shit hang on i have an idea

regal marsh
#

i don't want to limit sound effects in general, i just want to limit the number of sound effects of a specific type that can play at a time

polar marten
#

yeah

#

i think you're supposed to use the audio mixer for stuff like that

regal marsh
#

oh ok

polar marten
#

i'm not sure

regal marsh
#

i just found out that PlayClipAtPoint is a thing and that's basically exactly what i need lol

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.

fluid moat
#

Hi, I have a functional save system that saves data in binary (local) and need upload to DB, there its a simplest way to just upload that files on db? like "save that on that path instead of this one", Im struggling a little, with the info that I found works for saving data on tables directly but not at all what I looking for

proven plume
leaden ice
fluid moat
#

Ok foa I have a simple crane system where you can grab obj (containers) that have types and depending on type, a score (ex: metal, wood, etc).

You can grab and move around that containers but if you put them on a certain area, you win score (that is irrelevant actually)
My boss asked me to make a save system to save obj "last position" (also types) so I burned my brain to make a save system using binary formatting and in simple words it works like this: Get all containers in scene and their data, and save it (locally), when you Load that data it instantiate new obj with that data so basically it clones them (first delete the old ones and create the new ones in their saved positions)

I know that its not optimizated at all but it worked so...

#

my last task was in words of my boss "yeah but If a someone play I want to store that bc if another player use the app it recover the first player state"

#

(the app is on webgl)

#

so p1 -> plays on him pc -> exit -> p2 plays on his pc -> load p1 state -> continue -> repeat

#

that is the reason that I need to implement DB but not throw the save system that I have T.T

#

I tried with simple mysql projects but their just write directly on DB table, Im already saving a file so I want to:

#

Instead of saving that file on localrow bla bla in a blob table that has the columns defined for that files

#

save system p1

#

savesystem p2

simple egret
#

Oh well, good thing you want to change that

#

BinaryFormatter is insecure and opens vulnerabilities for your app, it should not be used anymore

fluid moat
#

some help? any advice?

simple egret
#

What does the DB look like right now? What DBMS are you using? SQL? NoSQL? Do you have tables already created? Do you have an API that will relay the game state to the DB and back?

#

It's quite a bit of work to switch from files to a database

#

(you can scrap the API if your database is local or embedded like SQLite)

fluid moat
#

rn im using MySQL and created a table with blob type for the files, dont get me wrong, know that bin is not good at all but dont wanna burn myself working on a new system, just being able to upload that files directly (idk if via http request or something)

simple egret
#

The computer that has the MySQL server, is it local or remote?

fluid moat
#

at the moment is local, but in the wet dreams of my boss it would be a server

#

thanks i ll read that

simple egret
#

On a server you'd basically want an API to interface the database, so you can add validation, auth and various other security checks

leaden ice
simple egret
#

And you'd also want a proper database structure. One table where you dump binary data is not really the use case for a DB, in that case you'd just have an API that reads and writes files on the filesystem directly

austere surge
#

I have a small coding question ig, I am not entirely sure in which channel it belongs and since I am not much experienced with coding I guess its alright to ask here xd

I am currently trying to learn about Character Movements in Unity. And for that I had to create different States for the character. In the tutorial I am watching the youtuber is writing some code. And he swapped the MonoBehavior to something else. (in this case he named it "IState"). My problem now is that whenever he does that the letters are yellow though mine just stay white. I marked the specific line in the screenshot with a comment.

leaden ice
#

But yours are white because your IDE is not configured

#

You need to configure Visual Studio to work with Unity properly

#

!ide

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.

austere surge
#

yeah he said something about the ide

#

ooh

#

i'll check it out, thank you!

austere surge
#

somehow the unity api wasn't connected to vs

#

thank you :)

rain saffron
#
    private RaycastHit hit;
    private Ray ray;

    private void Update()
    {
        ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(ray, out hit))
        {
            print(hit.triangleIndex);
        }
    }```
#

What would cause this to return -1?

#

Works with a cylinder, but not a cube.

leaden ice
#

not for any other kind of collider

rain saffron
#

Oh oops!

#

Didn't realize I'd not switched it out

#

Thank you 🙂

simple echo
#

Hi!

#

So I want to create a maze using the depth first search recursive backtracker algorithms.

I have the code for the algorithm but have a bunch of errors in it. I wanted to ask, if this algorithm would generate the walls of the maze ? Or is that something I have to draw using assets ?

simple egret
#

Can't say without seeing the code, I guess

#

Some algorithms just draw the maze in a 2D array in C#, then you have to replicate it physically in Unity

#

Some do it all at once

simple echo
#

Sure I’ll send a screenshot of the code in a minute

simple egret
#

No screenshots please

simple echo
#

Oh

#

How do I send it then. copy paste ?

simple egret
#

Post code according to the !code guidelines

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.

simple egret
#

Consider "large" as greater than 20 lines

scenic creek
#

Is there a way to ignore rotation around a given axis?
I have a camera which takes the player's rotation and adds onto it. So if the player is sideways, the camera is sideways. If the player is upside down the camera is upside down. The problem I'm having is that the player turns based on the camera's direction. This is creating a feedback loop. I want to make the camera use the rotation data of the player minus their local y rotation.

#

By feedback loop what I mean is that if you move mouse to look left, it will continuously move left and never stop.

leaden ice
zinc parrot
#

was there a way to change the #define of a shader from a script?

scenic creek
#

I have this in the camera script update method

input = cameraInput.action.ReadValue<Vector2>();
if (invertX) input *= Vector2.right * -1;
if (invertY) input *= Vector2.up * -1;
input *= sensitivity;
//input = new Vector2(1, 1);
yaw = (yaw+input.x) % 360;
pitch = Mathf.Clamp(pitch-input.y, minPitch, maxPitch);
Quaternion baseRotation = Quaternion.Euler(aimTarget.rotation.eulerAngles.x, 0, aimTarget.rotation.eulerAngles.z);
Quaternion rotationDelta = Quaternion.Euler(pitch, yaw, 0);
Quaternion rotation = baseRotation * rotationDelta;

Physics.SphereCast(aimTarget.position, camera.nearClipPlane, rotation * Vector3.back, out RaycastHit hit, distance, hitLayers);
if (hit.collider)
{
    transform.position = hit.point + (hit.normal * camera.nearClipPlane);
}
else
{
    Vector3 offset = rotation * Vector3.back * distance;
    transform.position = aimTarget.position + offset;
}
transform.rotation = Quaternion.LookRotation(aimTarget.position - transform.position, aimTarget.up);

and this in the player controller.

Vector3 forwardFromCamera = Vector3.ProjectOnPlane(sd.camera.forward, upDirection);
Quaternion targetRotation = Quaternion.LookRotation(forwardFromCamera, upDirection);
rigidbody.MoveRotation(
    Quaternion.Slerp(
        transform.rotation,
        targetRotation,
        Quaternion.Angle(transform.rotation, targetRotation) / 360
    )
);
solemn raven
#

Hey, is it possible to clone a gameobject that is not a (PREFAB) ?
meaning it's already a clone in the scene

pearl radish
#

Yes, Instantiate it

sage tundra
#

hey, why is my script not able to draw the square? (this script is applied to a UI canvas, parent to a rawimage object.) everything works as intended, but calls to Texture2D.SetPixel() don't seem to work? none of the safe checks that throw exceptions get triggered, so I don't know what's wrong.

solemn raven
# pearl radish Yes, Instantiate it

I thought instantiate only works on prefabs ( a gameobject that has a file on the drive ) , can it also clone a gameobject from a clone on playmode?

pearl radish
#

It can Instantiate any UnityEngine.Object

#

Components, GameObjects etc

solemn raven
#

ok cool , thanks a lot 🙂

fluid lily
#

I have the fallowing code.

    public struct Handle : IHandle {

        public UnityEngine.PropertyName _id;
        private IHandle _decorator;
        IHandle IHandle.Decorator { get => _decorator; }
        PropertyName IHandle.ID { get => _id; }

        public static readonly Handle Handle_Null = default(Handle);

        public Handle(string id) {
            _id = new UnityEngine.PropertyName(id);
            _decorator = Handle_Null;
        }

        public Handle(string id, IHandle decorator) : this(id) {
            _decorator = decorator;
        }

        string IHandle.HandleString => throw new NotImplementedException();


        public Handle Last() {
            if (_decorator is object && _decorator != Handle_Null as IHandle) {
                return _decorator.Last();
            }

            return this;
        }
    }

My question is on the Last() willthe _decorator != Handle_Null as IHandle work? I know struct is value type, so will the as mess with the comparision?

#

I imagine also implementing an isNull bool prop would solve that issue, and have it only be set to true on that one Handle. So then I can call isNull on the interface.

simple egret
#

You should be able to just do

if (_decorator != default)
  return _decorator.Last();
#

Members of interface types that are not assigned are null, so you could also do != null or is not null or is IHandle

#

Hell, push it further with a one-liner

return _decorator?.Last() ?? this;
fluid lily
#

I have to assign it before exiting the constructor. But that does work nicely. Still a little foggy on how default works in general I guess.

polar marten
#

what are you trying to do

simple egret
#

Yeah it all depends on the type you pass to it or what it inferred. default alone will try to infer to the type being compared or assigned, here it evaluates to default(IHandle) which is null since interfaces can be null

scenic creek
fluid lily
#

I am making an identifier, that can be "decorated" of sorts by other identifiers. I need a null reference to know if there are no decorators.

polar marten
#

what is this for?

#

what is the y of your xy problem

simple egret
#

(you don't need the null-ref static field anymore, just assign null or default in the constructor)

polar marten
#

right now it looks like complete warble garble

#

like it was made by an AI

#

i have a feeling you are translating something from e.g. C++

#

or some other idea

#

like just say what this is for

simple egret
#

Yeah ngl this seems wonky, the mix of regular interface implementations and explicit ones does not help

fluid lily
# polar marten what is the y of your xy problem

I am making a notification bus of sorts, there are multiple receivers for a base handle(like "Player.Actions") and then there can be sub handles(Like "Jump"). A notification can decorate itself so any Receiver looking for all handles "Player.Actions" can receive it, as well as any Receiver looking for "Jump" Handles. The PropertyName is for interactions with the Playables API.

polar marten
#

the Playables API

#

this game, it's like a narrative game? are you saying it's a quicktime events game?

#

like Heavy Rain or whatever

#

or what kind of game is it

fluid lily
#

This is just a system within the game? I have IoC to decouple code, and this notifications system allows code to hook into these Events or notifications without knowing anything about the code. The type of game is pretty irrelevant.

polar marten
#

well what is your goal?

#

we can talk about a good way to approach game architecture, or you can talk about exactly what you want to talk about, which may not necessarily make any sense, not in any concrete context anyway, like a video game

#

it's up to you

#

i am personally not super interested in talking about stuff that doesn't make sense

fluid lily
#

To have a decouple systems? There is the player graphs system already, but the notifications is pretty rudimentary. For example I can have the player "interact" with a scene load object, have that object send out a notification to the root scope for what scene to load, and any system listening for a scene load to do what it needs to do. I also can decrease the number of listeners by having them specify what scopes they listen on.

polar marten
#

To have a decouple systems?
hmm... but why?

#

like what is the game

fluid lily
polar marten
#

what are you trying to do?

polar marten
#

and i've only seen like, one snippet

#

so it's up to you

#

you can have a conversation* or not

#

you can tell me what the game is

#

or not

#

maybe there isn't a game

#

is there a game?

#

is it like a vrchat sort of thing?

#

that's still a game

#

like is it a casual world lobby?

#

alright well i gave it a shot good luck on this journey

fluid lily
#

Wou I am busy I am not ignoring you

simple egret
#

You can feel free to ignore them. Doc is the type of questioning design patterns rather than pure problem solving

#

(They do this all the time)

fluid lily
# polar marten i think if i polled all the senior unity developers i know, they would pretty mu...

My current game I am making is a simple point and click just to work out the kinks(and this is way over kill for), but this system is something I have been making for a longer time, and something I will continue to iterate on. The specific Handle probably can be done in a better way, but the notifications system is pretty standard design from like .net. As well as a bit of just faafo. None of the IoC systems I have seen have made me happy for Unity(though if they ever upgrade to .net 6 there are others I like), and this current problem is because of Unity's Playable system needing PropertyName, where I was happy with type comparison personally(so you can just have a Jump type that inherits Notificaitons.Actions).

#

If there is a better way around the problem with Unity's Playables system I would love to know as I am pretty annoyed with having to deal with it already.

fluid lily
#

As well Service Locator is IoC and is easy, but I am not a fan.

#

Likewise though Player Graph technically would be a NotificationsBoard it just sends every notification to every reciever, leaving the checking logic to the receiver which it really shouldn't have.

fluid lily
polar marten
#

are you making a library? for whom or for what?

fluid lily
#

I was going off of what Unity did for PlayableHandle class, and now not sure why they did that?

fluid lily
# polar marten are you making a library? for whom or for what?

I mean if it is good and works I will release it as an IoC library yeah. For any video game that wants DI and a more complex Notifications system(though will have those as separate modules). My DI gets all references of INotificationReciever, and with a custom attribute will assign them to the associated handler for their DI scope. My future game I want to make is a multi player game like Fallout/skyrim(trinket goblin) so stuff needs to be done through notifications or some way to network the calls(not finalized but more the faafo approach as I am a one man team at the moment). Like wise I have been studying programing architecture and this has been a great way of having it make sense.

polar marten
#

that is your goal?

fluid lily
#

more or less yeah.

polar marten
#

do you feel comfortable writing C++?

#

it's okay if the answer is no

#

like i don't like C++

#

just a simple yes or no

fluid lily
#

I had classes in college, but since then haven't touched it as much. I know the concepts and could switch over to it if there was a much easier way.

polar marten
#

gotchya

#

well unity is sort of one of the worst engines ever written for making a realtime, networked multiplayer fps

#

the gulf between what it alleges it can do and the tools it gives you to achieve a networked multiplayer fps, and actually writing one, is actually bigger in many cases than writing a basic one from scratch with a more barebones engine

#

if you wanted to do this, you should start learning DOTS, which is basically like learning a different game engine entirely

fluid lily
#

Fair, having faced problems with the lack of multithreaded/async support already on other projects.

polar marten
#

and the C# in DOTS isn't really C#

#

unity in general is a very poor fit for realtime multiplayer games

#

it actively gets in your way, because all of the nicest parts of its toolset are explicitly incompatible with a networked FPS, like the physics engine

#

IoC and Handles will not bring you closer to this goal

#

even if you used Unreal, you'll discover that the out of the box multiplayer is also kind of garbage, despite seemingly being a real multiplayer FPS engine.

#

the last two big 3rd party engine networked FPSes were valorant and apex legends. valorant they spent like 7 years developing, and they needed 20 people to more or less rewrite the state of unreal they had at the time, to behave as well as CSGO did, a truly ancient set of ideas

#

apex legends was made by a much smaller team on the source engine

#

if you put a gun to my head and said, make a networked multiplayer FPS, i would use the source engine

#

but i would also not aspire to make that kind of game

#

you can study how the source engine works and try to port those ideas to unity, but you'll be rewriting a game engine from scratch

#

if you are imagining a game with a design space of like overwatch

#

you know, no single person is going to be able to deliver that

fluid lily
#

I went head long into this as I needed to learn DI anyways, and figured it would at least give me a fun tool for other smaller games I wanted to make that could benefit from a local notifications system(like time control from undoing command pattern type stuff). The target game idea is a long ways off, and have approached all this knowing that, though each smaller game I have been making is to make pieces towards that ultimate idea. I appreciate the advice though, and definitely am not gonna need to know all that for now.

#

This Notification system was actually done, and then I wanted to add integration for the Playables systems. Was extremely nice to use, if not a bit performance heavy for the time being.

polar marten
#

and FindObjectOfType

#

for "service discovery"

#

it has all this stuff

fluid lily
#

Anyways I have to go, though thank you again for the feedback.

sharp ingot
#

Would anyone happen to know what could be causing this error?

fresh yarrow
#

is there anything wrong with this script?

#

using UnityEngine;
using System.Collections;

public class CharacterController : MonoBehaviour {
private Rigidbody rg;
public float speed = 10.0F;
public float jumpspeed = 10.0F;

void Start () {
    Cursor.lockState = CursorLockMode.Locked;
    rg = GetComponent <Rigidbody> ();
}


void Update () {
    float translation = Input.GetAxis ("Vertical") * speed;
    float straffe = Input.GetAxis ("Horizontal") * speed;
    translation *= Time.deltaTime;
    straffe *= Time.deltaTime;
   
    transform.Translate (straffe, 0, translation);
   
    if (Input.GetKey (KeyCode.Space)) {
        Vector3 atas = new Vector3 (0,100,0);
        rg.AddForce(atas * speed);
    }
   
    if (Input.GetKeyDown ("escape"))
        Cursor.lockState = CursorLockMode.None;
   
   
}

}

sharp ingot
#

there is already a Unity Defined CharacterController class, no?

stable rivet
sharp ingot
timber snow
#

I'm writing an editor script that generates a palette and an indexed image from a source image, and i need the script to save the texture2Ds i'm building as PNG files
texture2D.EncodeToPng(); gives me a byte[] that i can write to a file, but to do that i need to use System.IO to write that data to a file
but the file system is different between System.IO and unity's AssetDataBase class
is there a clean way to save a PNG as a unity asset using AssetDataBase? I can do CreateAsset(path, texture) to save the generated Texture2D, but this isn't a PNG

keen eagle
#

I'm planning this to use as background using sprite renderer. Image has 20% opacity but my problem is unity doesn't recognize the opacity. What can be the problem?

vagrant agate
keen eagle
visual flare
#

what's a more condensed way to write this, without linq?

leaden ice
#

I mean that's pretty much as condensed as it gets

#

Other than removing whitespace and brackets

#

Maybe h.dirty = h.hull == null; but that's logically slightly different behavior.

mossy wadi
#

Does anyone know where Texture2D.EncodeToPng() went? I'm using 2021.3.16f1 :/

mossy wadi
cosmic rain
mossy wadi
cosmic rain
#

You need to make sure you have the module.

#

Package manager?

mossy wadi
#

cant seem to find it 😦

#

Oh, I found it!!

#

Thanks!

#

man, they really over-complicated that one!

cosmic rain
mossy wadi
# cosmic rain Where did you find it?

I found it in Built-in packages in the package manager. I just complain because it used to be so easy, but I guess this works. Just needs better visibility and direction imo

cosmic rain
mossy wadi
#

this is a fresh project

cosmic rain
#

Weird. But oh well.🤷‍♂️

void basalt
#

is mouse Input.GetAxis the delta of the last frame or the last call?

visual flare
#

but yeah like you said it's not exactly the same because it always overwrites .dirty so it could be ternary instead like h.dirty = h.hull == hull ? true : h.dirty or just h.dirty = h.hull == hull || h.dirty

#

or even

cosmic rain
cosmic rain
leaden solstice
#

ForEach is not Linq 😉

cosmic rain
#

Hmm

#

I guess it's not then.😅

leaden solstice
#

However it shares downside of Linq, slower than foreach and closure allocation

leaden solstice
#

But what are you trying to do

polar marten
nimble kernel
#

Does anyone know how to access the audio source component's listener distance value? It's calculating it for the component but it doesn't seem to be exposed. I shouldn't have to calculate it a second time so that I have my own copy of it.

tough osprey
#

FFS. Working with BatchRenderGroups and Shaders and thinking my issue is my lack of understanding of those concepts ... then I see it ...

for (int i = 0; i < _numInstances; i++) {
    Matrix4x4 matrix = Matrix4x4.Translate(computeTransform(i));
    matrices[i] = matrix;
    objectToWorld[i] = new PackedMatrix(matrix);
    worldToObject[i] = new PackedMatrix(matrix.inverse);
    terrain[i] = Random.CreateFromIndex(1337).NextInt(0, 2);
}

I couldn't figure out why I wasn't reading the Terrain value of 0 or 1 on a per instance basis and I was instead always reading the same value ... at least it feels so good to have it working now ...

keen eagle
sick compass
#

Hello

simple mountain
#

How do you make a svg file from a string and upload it to a spriterenderer?

stray solstice
#

Anyone knows if there's a way to check if a Directory.Exists using Application.streamingAssetsPath on Android?
There's BetterStreamingAssets plugin that helps with some utility methods, but it only has GetFiles and no HasDirectory

eternal bear
#

I need help fixing this error code

Assets\Scripts\PlayerMovement.cs(203,44): error CS0103: The name 'Math' does not exist in the current context

eternal bear
#

Ye

grand hemlock
#

guys how do i declare a list of tuples?

#

is it just

List<Tuple> blabla
```?
main shuttle
#

Google: "how do i declare a list of tuples C#" it will tell you everything about it.

grand hemlock
#

its not actually showing me how to declare one

main shuttle
#

This is the first answer for me in google.

grand hemlock
#

all it showed for me was Tuple Deconstruction

simple mountain
#

How do I check if a point is on a line from a to b given a thickness variable?

main shuttle
grand hemlock
#

because u could use gradients

simple mountain
#

for now yes

main shuttle
grand hemlock
#

aka ratio between the x and y position

#

i think it was smth like

Vector2 gradient = new Vector2(B.x - A.x, B.y - A.y)
float ratio = gradient.y / gradient.x
simple mountain
#

Can you explain how you would find out weather the point is on the line using a sphere cast?

main shuttle
grand hemlock
#

to make it simple just use colliders

simple mountain
#

oh so you mean I draw a box from a to b and check if [CheckThis] is inside it?

simple mountain
simple mountain
grand hemlock
simple mountain
#

yes

#

that s what I learned too

#

I'm just not sure how I could apply it to this usecase

#

so you are making a function m*x where A is coordinate origin?

simple mountain
flint orchid
#

Hey gang, would anyone have a minute to help me with some strangeness regarding SetTemplateCustomValue and WebGL templates?

grand hemlock
#

you can check

#

whether BC is parallel to AB

#

if it is

#

then C is in the line AB

#

unless its behind B

simple mountain
#

yes that is actually what I was trying to do here

grand hemlock
#

idk abt the width part tho

hexed pecan
#

@simple mountain Make (or google) a function that finds the distance from a point to a line

#

And check if that distance is less than the radius

simple mountain
#

Yes i m trying to make one

hexed pecan
#

Its basically a capsule check

hexed pecan
grand hemlock
#

if ur struggling why not just use triggers?

simple mountain
#

Triggers?

grand hemlock
#

colliders

simple mountain
#

I'm trying to make a shader..

hexed pecan
#

You dont always want gameobjects and components for calculations like this

grand hemlock
#

u never told me that tho

grand hemlock
simple mountain
#

ye sry

grand hemlock
#

yea idk anything abt shaders

simple mountain
#

It s just math

hexed pecan
#

You'd want something like

float DistanceToLine(Vector3 point, Vector3 a, Vector3 b)
{
  return Vector3.Distance(point, NearestPointOnLine(point, a, b));
}```
#

@simple mountain Does that make sense

#

Not shader code but you get the point

simple mountain
#

yes that makes sense I'll just have to find out what NearestPointOnLine does on it s inside

hexed pecan
#

(You want the finite version)

simple mountain
#

Ye thank to both of you

grand hemlock
#

guys when i try to loop thru the contents of a dictionary this error pops up
Assets/GenerateDungeon.cs(84,73): error CS0122: 'KeyValuePair<Vector2, float>.key' is inaccessible due to its protection level

#

here is the code which is causing the issue

        foreach (KeyValuePair<Vector2, float> entry in corridors){
            GameObject new_corridor = Instantiate(corridorObject, entry.key * distance, Quaternion.Euler(0,0,entry.value));
        }
grand hemlock
#

ohh

cold parrot
#

And set up your ide

grand hemlock
#

im using vscode for a little bit

cedar pivot
grand hemlock
#

its temporary

grand hemlock
cold parrot
#

there is no single right way to do it and it depends a lot on the specific game

cedar pivot
#

hmm got it thanks

simple mountain
#

works suprisingly well

lusty dragon
#

I need to wait MoveCameraToHouse() to finish before showing the tutorial. Any Idea what kind of Wait<>() I need to use?

 IEnumerator InitializeGame()
    {
        MoveCameraToHouse();

        ShowTutorial();

        yield return new WaitForSeconds(2f);

        MoveFamilyToHouse();
    }

The code in MoveCameraToHouse() is the following (if that helps):

    void MoveCameraToHouse()
    {
        LeanTween.moveX(camera_go, 4, 5); //package
    }  
grand hemlock
#

guys why is unity showing this error despite RoomObject is clearly declared in the inspecting
UnassignedReferenceException: The variable roomObject of GenerateDungeon has not been assigned.

lusty dragon
#

Oh , I can use the time in the function which is the third parameter. 😛

grand hemlock
#

roomObject is not mentioned anywhere else

prime sinew
#

wait, it's saying it's not assigned

#

so, where is it supposed to be assigned?

thin aurora
#

Make sure that it is assigned and that a prefab overrides its values, should you use that

muted idol
#

I was able to virtual click the button with ExecuteEvents.Execute but I'm having some problem on how to do virtual mouse dragging event. Anyone know how to do it?

lusty dragon
#

Is update of fixed update the one that is going to have the same time for every device?

main shuttle
lusty dragon
#

I have a game for kids that has a house with several electrical problems that occur randomly in the building. So every now and then I need a countdown to finish for every device and a warning to popup. I want the countdown to be the same for every device and not make the .exe with a result of a countdown that is slower/faster than in the editor.

prime sinew
lusty dragon
#

Alright. Got it thank you

brave violet
#

hey folks, does anyone have experience with save data being corrupted when the system loses power? I need to support a situation where the PC will be turned off at the power source without being properly shut down but my game's save data gets corrupted. any help or experience would be appreciated 🙂

I've made a forum thread with a little more info here: https://forum.unity.com/threads/saving-data-when-system-power-is-lost.1397206/

west lotus
#

You can also keep the last save so have a autosave and a autosave_old and fallback to the old if latest is bad

brave violet
#

thanks for the reply. I am doing periodic saves, and this isn't a case where it's killing the power WHILE data is saving.

#

but data is being lost nonetheless

brave violet
west lotus
#

you cant do anything about that exept dont overwrite the previous successful save

west lotus
brave violet
#

apologies, I'm not too experienced with data writing. what does it mean to "do a hash of the data"?

west lotus
#

lets say your save data is a json string. You would put that json string into what is called a hash function(there are many). That function will give you a bunch of numbers and letters as a result

#

then if you put the same exact string again at a later time you will get the same sequence of numbers, if it's different by even one letter you will get a wildly different sequence

#

this is essentially called a checksum you can read up on it

brave violet
#

ah OK, so you would have some constant value that should never change, and you can use that to check if everything is saving correctly?

west lotus
#

yes

#

you can put the checksum at the end of the file, or the begining

#

or even have it be the filename

brave violet
#

gotcha

prime sinew
#

not sure what you mean, but have you used the rigidbody constraints in the inspector?

oak topaz
#

var rot = Quaternion.FromToRotation(transform.up, Vector3.up);
rb.AddTorque(transform.forward * new Vector3(rot.x, rot.y, rot.z).x * TiltSpeed);

crude jungle
#

do i ask here for help ?

oak topaz
#

atleast i think

cosmic rain
crude jungle
crude jungle
#

ok so basically I have a ball and I want to like make it dash to the position of where I clicked with the mouse ( or tap on the screen ) i also want it to slow down by time

#

Also how do i make the controlling look like this , like the more you push the mouse the higher speed you get ?

#

for now i have this and what it's doing is just launching the character in the direction of where i click the mouse

using UnityEngine;

public class Dashing : MonoBehaviour
{
    public float dashSpeed;
    private Vector2 dashDirection;
    private Rigidbody2D rb;
    private bool isDashing;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            dashDirection = (mousePos - (Vector2)transform.position).normalized;
            StartCoroutine(Dash());
        }
    }

    IEnumerator Dash()
    {
        isDashing = true;

        while (isDashing && (Vector2)transform.position != dashDirection)
        {
            rb.velocity = dashDirection * dashSpeed;
            yield return new WaitForFixedUpdate();
        }

        rb.velocity = Vector2.zero;
        isDashing = false;
    }
}

cosmic rain
#

Does it need physics involved?

crude jungle
#

if you mean falling and gravity then ye

cosmic rain
#

Does the movement need to be physics based?
If you're new, then why post here? Didn't I say that this channel is for around intermediate level?

cosmic rain
#

Does it not need to reach the target point?

crude jungle
candid mist
#

just in terms of best practice, should i handle sensatory checks from an ai in a behaviour tree, or elsewhere?

cosmic rain
cosmic rain
#

Ok, so you've got the movement part working. Is it just the scaling of velocity based on the drag distance that you miss?

crude jungle
#

also the draging system

cosmic rain
#

For dragging, you need to cache the position of the pointer on pointer down, then get the position at pointer up. You can use the distance between these 2 vectors as a multiplier for your velocity.

oak topaz
oak topaz
potent glade
#

help please im getting "ios version hasn't been set up correctly"... i made my game on android (using windows) then imported the files into a mac... I made a new project in man, replaced assets.. project settings and packages with the old ones ... and started to build ... is there anything wrong with the steps i made

lusty dragon
#

I run this in Update():

void FollowThePath()
{
  // Check whether the pathCreator exists
  if (pathCreator != null && isAllowedToMove)
  {
    // Move accordingly
    distanceTravelled += speed * Time.deltaTime;

    // Apply that movement towards the next point and until the end of the path
    transform.position = pathCreator.path.GetPointAtDistance(distanceTravelled, endOfPathInstruction);
  }
}

how'd you guys check whether my agent has reached its destination?

vagrant blade
#

Check the distance between it and your destination is small enough

quartz folio
#

if the path has a distance property then you could compare it with distanceTravelled

keen eagle
#

Hi I tried creating a custom material but it turns into pink

#

I already set the Scriptable Render Pipeline Settings to URP

leaden ice
#

hence the pink

#

it's not compatible with URP

#

Also this is not a code question at all, you're in the wrong channel

keen eagle
#

oh sorry

worldly hull
#

im asked to create a quite complicated quest function where certain quests can only be unlocked after a real life time delay

for example, after i finished quest A, quest B needs to wait for 3 hr to unlock (like 4PM - > 7PM), i already have a server that can allow me to store it , but still quite dont know what to do

#

if anyone here played genshin before, u will know what im talking about, certain quests needed to wait for next day for it to unlock

olive crypt
#

One solution could be to start a long-running task that will await the amount of time before unlocking the quest(s)

Note, however, issues may occur if the user closes the app.
Therefore, when the user logs out of the app, you would cancel the long-running task, and set some sort of flag to check the quest refresh duration the next time the user opens the app - if the user logs back in and they haven't waited long enough, simply start the long-running task again for however much time is left.

Just to say this is a solution and not the solution, I don't know if anyone else has any better ideas :)

thick socket
worldly hull
#

lmao

west lotus
worldly hull
#

the team lead wants to use hard systems to compensate the blank mini game nature of it

olive crypt
thick socket
west lotus
#

Good talk😀

swift falcon
#

how can i get a variable/reference/value from unity's default assembly inside some asset's namespace so that i can use it in its scripts?
i think i need to make another assembly and include it in the asset's scripts

leaden ice
swift falcon
#

I create physics scene in a script without namespace

#

and im trying to work with it in (to send the value to) scripts with namespace

#

but they dont see it cuz assembly

leaden ice
#

Are you trying to make changes to unity's code or something?

swift falcon
#

No just to an asset from unity's store

leaden ice
#

generally you should try to avoid making changes to them

worldly hull
#

i think i will break the system to small steps first

leaden ice
worldly hull
swift falcon
#

so i kinda have to edit it (and replace default raycasts with PhysicsScene.Raycast)

oak topaz
worldly hull
#

im so dead rn

oak topaz
#

Ik lol ijk but srsly tho.. how would you do that

oak topaz
leaden ice
#

such as the physics scene

#

then you won't have any assembly issue

west lotus
worldly hull
#

ok i will keep a look at it

#

wait i found something like datetime

west lotus
#

Well if you check time on a users device they can manipulate that

worldly hull
#

maybe it will help

west lotus
#

You can do a request to some of the time servers on the net

#

Like a NTP server

swift falcon
# leaden ice such as the physics scene

Yea but the only way to get a physics scene reference is to create it i believe... which means i would need to create the physics scene from within the asset that is only using it but is not actually a part of it, and it wont be the only script using it either
it just feels more clear to me if I dont do this

leaden ice
#

also if you have a GameObject that is in the physics scene, you can get the physics scene reference from that without any additional parameters etc

worldly hull
brisk marsh
#

Heyo

olive crypt
#

Hi guys, I find myself running into the same issue over and over but I can't describe it well enough that it's accessible via a Google search

It's presenting itself at current whilst I'm trying to make a weapon attachment system - I need to be able to specify which types of attachment are valid, so I added a List<Attachment> validAttachments; to my AttachmentPoint class.
The issue I see here is that that is a list of instances of attachments, not a list of types of attachment - this requires an instance of every attachment which will just take up memory, and does not seem intuitive
To my understanding, it also doesn't make sense to use List<Type> validAttachments; because there isn't a way to edit that within the inspector
I then thought about using enums but I don't particularly want to edit an enum for every new attachment I add to the game
Finally, I thought I could use interface implementation to have a string constant for each attachment type that could be checked, this seems somewhat feasible
If anyone has any solutions or examples of how to create a list of valid attachment types it would be immensely helpful, I run into this problem in many other aspects of the game :)

brisk marsh
#

Got a question - Is it possible to bypass using the MenuItem attribute and directly create a new Menu Item through C#? (moved from Code-advanced because it's not advanced)

deft pebble
rain minnow
olive crypt
thick socket
#

enum thingytype
{
scope
clip
rail
etc
}

#

when when seeing you can just check the type

timber cloak
#

I have a dictonary int as keys and an 2d array of the type cell as the value. When i am making the array i do Dictionary.add(int, new Cell[10,10]), but when I am accesing x,y it says that it is a null. But when initelizing the array should it not make thoose automaticly. or do i need to do something else becasue of it is a special class

rain minnow
hollow stone
#

It's possible to set things up with SOs you'd keep the set of SOs for different attachment per gun.

thick socket
#

(if you don't want each type of scope for each weapon) just have like scope/reddot/holosight for enums

thick socket
hollow stone
thick socket
#

then it doesn't break serialization

hollow stone
thick socket
#

for the most part you shouldn't be changing enums anyway

#

¯_(ツ)_/¯

olive crypt
#

Hm yeah I suppose a list of SOs could work, for a while I was trying to avoid them however it is along the lines of how I want the system to work

And although I get what you are saying with the enums, Hawk, it's quite possible I would need to specify every single item as an enum :)

rain minnow
thick socket
#

main reason I use enum is so it will autofill and I don't have to worry about typos with something like strings

hollow stone
thick socket
#

unless you are using Strings...which I don't like cause typos

rain minnow
# thick socket how would that look like?

basically, it's an SO used as an enum value. instead of selecting from a enum dropdown, you drag the SO into your type field and compare that instead. it's versatile because you can write code inside of those SOs to do specific things. it's a great replacement for using an enum with a switch statement . . .

cedar pivot
#
using UnityEngine;

public class Movement : MonoBehaviour
{
    private Player player;
    private Vector3 moveDirection;

    private void Awake()
    {
        player = GetComponent<Player>();
    }

    private void Update()
    {
        if (player.IsControlling)
        {
            player.State = Player.PlayerState.Controlling;

            float xDirection = Input.GetAxis("Horizontal");
            float zDirection = Input.GetAxis("Vertical");

            moveDirection = new Vector3(xDirection, 0, zDirection);
            moveDirection.Normalize();

            if (xDirection != 0 || zDirection != 0)
            {
                player.IsControlling = true;
                player.State = Player.PlayerState.Controlling;

                HandleMovement();
                HandleAnimation();
            }
        }

        else
        {
            player.IsControlling = false;
            player.State = Player.PlayerState.Idle;
            HandleIdleAnimation();
        }
    }

    private void HandleMovement()
    {
        if (moveDirection != Vector3.zero)
        {
            transform.Translate(moveDirection * 8 * Time.deltaTime, Space.World);

            Quaternion toRotation = Quaternion.LookRotation(moveDirection, Vector3.up);
            transform.rotation = Quaternion.RotateTowards(transform.rotation, toRotation, 800f * Time.deltaTime);
        }
    }

    private void HandleAnimation()
    {
        if (moveDirection != Vector3.zero)
        {
            player.PlayerAnimator.SetFloat("forward", 1);
        }
        else
        {
            player.PlayerAnimator.SetFloat("forward", 0);
        }
    }

    private void HandleIdleAnimation()
    {
        player.PlayerAnimator.SetFloat("forward", 0.1f);
    }
}```

Guys... WHY IT DOESNT STOP RUNNING
thick socket
#

or what would actually be on the SO?

hollow stone
rain minnow
thick socket
cedar pivot
#

i didnt understand

thick socket
#

why not just 1 SO with 10 Lists? (each named 1 of the values)

hollow stone
thick socket
#

curious if its just cause SO get laggy after awhile or if another reason

thin aurora
#

So fix that first

fresh cosmos
#

how can i correctly parse a character of a number into the number its displaying`?

hollow stone
leaden ice
fresh cosmos
#

nice. thanks

thick socket
#
public class FireBall : Bullet
{
    protected override void Start()
    {
        base.Start();
        speed = 10f;
    }
}
public class FireBolt : Bullet
{
    protected override void Start()
    {
        base.Start();
        speed = 20f;
    }
}
#

if I want a bunch of different types like this...is there a better way of doing this?

#

(Im going to want to use Pooling for Fireball/FireBolt)

thick socket
#

If feels like I can't leave them all as bullets with an enum if I want different types for pooling?

leaden ice
#

why not just do:

public class Bullet : MonoBehaviour {
  public float speed;
}```
And set the speed in the inspector
regal marsh
#

This might be a bit of a stupid question but i'm gonna ask it anyways: Does calling WaitForSeconds(0)/WaitForSecondsRealTime(0) essentially skip it?

regal marsh
#

do you just not wait at all

leaden ice
#

it waits for one frame

regal marsh
#

good enough

thick socket
regal marsh
#

thanks

leaden ice
#

no need to use what you have

floral coral
#

how can I convert between vector2's and float2's to use a compute shader?
Also, I want to simulate gravity between multiple rigid boides (2D), should I use a float2 array to hold the position of each body?

leaden ice
#

no need to make separate scripts

deft pebble
regal marsh
#

well the reason i have it is because i'm calling it by passing in values for cooldowns depending on what i want, and some of those are 0 and some aren't

leaden ice
hollow stone
regal marsh
#

i'm not using it in the way you'd use yield return null

leaden ice
thick socket
leaden ice
#

make two pools, and you will have two pools

regal marsh
#

i'll look into that

leaden ice
#

assuming you mean Unity.Mathematics.float2

thick socket
#
protected virtual void Start()
    {
        //rb.velocity = new Vector2(1f * speed, 0f* speed);
        rb.velocity = transform.right * speed;
     }
#

is it bad if I leave it as protected/virtual if I dont end up wanting to inherit from base class?

leaden ice
#

probably not enough for you to notice

thick socket
#

gotcha thanks

deft pebble
#

You should choose extendibility and readability over those nano-optimisations

leaden ice
#

i mean I wouldn't make a method virtual for no reason. That is not creating any kind of meaningful "extendibility"

#

it in fact makes you think there must be something overriding it, which reduces readability when there actually isn't

floral coral
#

Do compute shaders only use RWTexture2D as data to read from and write to with a C# script?

leaden ice
#

RWTexture2D is specifically a texture

thick socket
#
public class BulletPooling : MonoBehaviour
{
    ObjectPool<Bullet> fireballPool;
    Bullet fireballPrefab;
    ObjectPool<Bullet> fireboltPool;
    Bullet fireboltPrefab;


    // Start is called before the first frame update
    void Awake()
    {
        fireballPool = new ObjectPool<Bullet>(CreateFireball, TakeBallFromPool, ReturnBallToPool);
        fireballPool = new ObjectPool<Bullet>(CreateFirebolt, TakeBallFromPool, ReturnBallToPool);
    }
    void TakeBallFromPool(Bullet bullet)
    {

    }
    void ReturnBallToPool(Bullet bullet)
    {

    }
    Bullet CreateFireball()
    {
        var bullet = Instantiate(fireballPrefab);
        bullet.SetPool(fireballPool);
        return bullet;
    }
    Bullet CreateFirebolt()
    {
        var bullet = Instantiate(fireboltPrefab);
        bullet.SetPool(fireboltPool);
        return bullet;
    }
}

this feels repetitive and like I should be doing it differently

#

for each type I'll have to make a function that does the same thing but 2 different params

leaden ice
#

you don't need to duplicate any code

#

and a Dictionary<ProjectileType, Bullet> prefabs;

#

then you can have like:

Bullet CreateProjectile(ProjectileType pType) {
  var bullet = Instantiate(prefabs[pType]);
  bullet.SetPool(pools[pType]);
  return bullet;
}```
#

no duplication

#

although really shouldn't the pools be handling instantiation?

polar marten
leaden ice
#

so wouldn't it just be:

Bullet CreateProjectile(ProjectileType pType) {
  return pools[pType].GetObject(); 
}``` or however the pool works
thick socket
#

one for making new item when there isn't one

leaden ice
#

yes

#

indeed

thick socket
#

retrieving it and returning it

rain minnow
true bramble
#

I am using a vector2 field here in the inspector, how would I change the Y label to say Z instead

leaden ice
#

you can't use Vector2Field
you have to create your own

thick socket
true bramble
#

how do I create my own

leaden ice
thick socket
#

inside the "create" function dont I need to return the item and instantiate a new one?

thick socket
#

👍

leaden ice
thick socket
#

my issue was I forgot I could do something like this to pass in a param lol

#
        fireballPool = new ObjectPool<Bullet>(()=>CreateFirebolt("10"), TakeBulletFromPool, ReturnBulletToPool);
leaden ice
#

yeah

true bramble
#

could I just copy and paste stuff from whats happening inside vector2field cos I cant get the widths and stuff right

leaden ice
#

and it would do that with the lambda

true bramble
#

where would I even find what EditorGUILayout.Vector2Field(); is doing

arctic ravine
#

what is this error?, im trying to fix this for 2 hours but nothing works

leaden ice
true bramble
#

what about using vector3feild and making the style of Y greyed out?

thick socket
#
 public Dictionary<BulletTypes, ObjectPool<Bullet>> bulletPools;
    public Dictionary<BulletTypes, Bullet> bulletPrefabs;
#

is there a way to set the 2nd dictionary in inspector?

rain minnow
# olive crypt Hm yeah I suppose a list of SOs could work, for a while I was trying to avoid th...

also, if you want multiple attachments for a certain type, it may be easier to have a rank field for each attachments, like an int or another set of SO enums. some guns can attach rank 0 and rank 1 scope attachments, but only rank 0 mag attachments. this will avoid making a list of all available attachments, as you just search if the correct type of attachment was selected and if it has the necessary rank . . .

arctic ravine
thick socket
#

Google didn't give an answer sadly

leaden ice
#

and just make a List or array of those

#

then loop through them in Awake to create the dictionary

floral coral
#

in the code

struct RigidBody2D_Data {
    int numberOfBodies;
    float2 position[];
    float mass[];
};

(for a compute shader)
how can I set the length of position[] and mass[] be numberOfBodies?
I think I can set it in a C# script, but unity gives me errors if I leave it like this.

floral coral
#

I thought it would fir here because this isn't about "shading" but for calculating gravity. I know it's a compute shader, but I'm not intending to use it to shade

thick socket
#
BulletPooling.Awake () (at Assets/Scripts/interactable/BulletPooling.cs:23)
UnityEngine.Object:Instantiate(Object)
BootStrapper:Execute() (at Assets/Scripts/DontDestroy/BootStrapper.cs:6)
void Awake()
    {
        instance = this;
        foreach (var bullet in bullets)
        {
            var tmpPool = new ObjectPool<Bullet>(() => CreateBullet(bullet), TakeBulletFromPool, ReturnBulletToPool);
            bulletPools.Add(bullet.bulletType, tmpPool);
//line23 is .Add line
        }
    }```
#

what is it throwing an error for?

#

I don't understand how it doesn't have an object...as it couldn't do the foreach without an object?

thick socket
#
bulletPools.Add(bullet.bulletType, tmpPool);
#

sorry tried to toss the comment in to say which was line23 😄

rain minnow
#

did you initialize or assign bulletPools to anything?

thick socket
rain minnow
#

whenever you get a null ref just check if each reference type variable on the line is assigned. easy peasy . . .

thick socket
#

totally forget that I have to do New() on things I create lol

#

appreciate it 🙂

timber cloak
#

The problem is that on line 139 i get an NullReferenceExeption and i can solve it by putting Floors[i][i,j] = new Cell; but that feels uneffective to do for every element. Prevoius i had the array as an enum list only and then it worked. So i believe the problem is with the cell class. Floors is a Dictioary with int as key and Cell[,] as value

late lion
thick socket
#
protected virtual IEnumerator ShootCoroutine()
    {
        // cooldown between multishots
        while (true)
        {
            if(pauseShooting==false)
            {
                // shoot for multishots
                for (int i = 0; i < attackStats.multiShot; i++)
                {
                    character.Animator.SetBool("Cast", true);
                    yield return new WaitForSeconds(0.15f);
                    //fireball = Instantiate(fireballPrefab, firePoint.position, firePoint.rotation);
                    Bullet fireball = BulletPooling.instance.bulletPools[BulletTypes.FireBall].Get();
                    fireball.transform.position = firePoint.position;
                    fireball.transform.rotation = firePoint.rotation;
                    fireball.Fire(attackStats.attackDmg, gameObject.tag);
                    yield return new WaitForSeconds(0.15f);
                    //yield return new WaitForSeconds(fireCooldown - 0.15f);
                }
            }
            yield return new WaitForSeconds(attackStats.attackSpeed);
        }
    }

multishots is set to 2, each shot should be shot at the 0.15 mark to match my animation...the first shot is shot correctly. The 2nd shot is shot at the 0.3/0 mark and not at the 0.15 mark...any idea why?

#

I have 2 0.15f waits in...so why isn't it waiting 0.3f before 2nd fireball shoots?

rain minnow
thick socket
#

I should be firing at each 0.15s

#

so it waits 0.15s fires once...waits 0.15s (animation ends)...wait 0.15s fires 2nd shot

#

animation takes 0.3f

rain minnow
#

what happens if you remove the 2nd wait?

thick socket
#

however my animation says it only takes 0.3f to finish?

rain minnow
#

this would probably be easier if you used an animation event that calls a method at a specific time during the animation. no need to try and time or sync anything up . . .

weak nacelle
#

I'm at a loss here, I have disabled almost all Intellicode functions, I have split up a ton of scripts for what seems to be no reason after all, Visual Studio's performance is cripplingly slow despite having tons of free resources on both RAM and CPU

#

Talking second long hangs every time you start typing or click with the mouse anywhere

thick socket
#

i could try and look into that

weak nacelle
#

Visual studio is using basically no RAM and doesnt tax the CPU at all

thick socket
rain minnow
glacial halo
#

Hi all,

I'm wondering if someone could point me in the right direction on what would be the best way to deal with game map.

The idea is that the green circle is a planet (easy), the blue ring is a flat ring surrounding the planet with a texture applied to look like planetary rings (this I think I know how to do with a shader so that it fades based on distance to player). If you look at the full size image there's a red dot which signifies the player position. And the 'noisy' section at the bottom of the image is 'physical objects', such as debris, asteroids etc.

The part I'm not 100% sure on what would be the best approach is the physical objects section. It's a pretty big area, so would be a lot of objects. Instantiating/Object Pooling would seem to be the obvious choices but I'm not sure.

Would anyone have any suggestions to approaches would work best?