#archived-code-general
1 messages · Page 34 of 1
Coding Riddle: Guess what hrt stands for.
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
use a singleton to keep score
have your objects call out to the singleton when necessary to increase/decrease the score
Heart? If not, then try naming stuff better so the usage can be guessed at first sight.
Lmao. I named it like that for the riddle
Pft, no one's guessing. No fun. Answer = HexRuleTile
And those cases are not even in binary, weird
Maybe that's just how Unity handles it anyway
The position of the int maps to directions. That way you can reverse the int and check for mirrored positions
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
shouldn't these be 0b000011 etc? Otherwise this is literally the number 11, which is 1011 in binary
Nothing in the code actually is reading binary
likewise you can make the enum use those bit patterns directly and then you would't need this switch at all.
it's just checking to see if the northeast tile matches, if so add 1 to the bitcode
What do you mean?
If you tell me my clever solution sucks, I will be both grateful and salty
To be honest it's not really clear what's happening here
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;```
Well the hrt.X are sprites. I assume you still need to do some kind of switch case to get the correct sprite
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
Well then I'll make it a dictionary just to not look like a noob, lol
okay thanks ! do you think that will require sufficient coding? i want to learn coding whilst creating the game :))
There are a lot of tutorials on making singleton
It's pretty simple
It just means you can access it anywhere without reference
ahh okay! i want to use something that is not unity's built in. so was intially thinking of Postgress
back up
you're jumping ahead to the leaderboard part
you need to get scorekeeping working in the first place first, just in the local game
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.
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
okay great thanks
I'm currently trying to get the horizontal angle between two points in degrees
You'll have to elaborate on this some more. The code you posted doesn't seem to be doing anything with angles. Could you draw a picture of what you want?
What is a "horizontal angle"?
the angle around the y axis
as in
imagine a transform facing another point in space
the y euler angle
of that transform
ok then you want:
float angle = Vector3.SignedAngle(a, b, Vector3.up);```
thank you
oh wait I just realized what you want and it's not what I gave you
You want this:
Vector3 dir = testFront.position - testBack.position;
float angle = Vector3.SignedAngle(Vector3.forward, dir, Vector3.up);```
ah thank you
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.
I don't understand what the purpose of having a SO is in your case?
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.
I only use SOs as readonly in my projects, but I know there are patterns https://unity.com/how-to/architect-game-code-scriptable-objects where they use to write in runtime to have different systems read the value.
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.
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.
Whats the best way to go about putting an object in here that is in a different scene?
you can't. you'd have to add the listener at runtime when both objects exist at the same time
Put very simply: you can't (directly). What you can do instead: call something on a different script and then locate the other instance to call a method on and execute it (assuming it's loaded already).
The Question is just: what do you want to use this for? There might be a better solution then the one you're looking for.
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
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?
I think that is the conclusion I am working toward. Can you elaborate on the data/model decoupling?
Reading the docs it seems WebGL isn't supported
Not in the platforms list:
https://docs.unity3d.com/Packages/com.unity.renderstreaming@3.1/manual/index.html
And in the FAQ section:
https://docs.unity3d.com/Packages/com.unity.renderstreaming@3.1/manual/faq.html UWP and WebGL are not supported.
FindObjectOfType<>() - does that search all opened scenes?
or just the main one (where the calling monobehaviour is)?
all objects loaded into the game world.
Note that there is no "calling" MonoBehaviour for that function. it is a static function
Like any MVC like pattern. https://blog.unity.com/games/level-up-your-code-with-game-programming-patterns
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 ?
Mathf.CeilToInt
Thanks ❤️
why Linq Where returns me a bool array instead of GO array?
i think its different Where, not the one in LINQ
yeah double check as it shouldnt do that
uh, i guess you could call the static method itself
I can't reproduce this issue locally, for me it resolves to the expected Where. Is it possible that you have another extension method in your project which returns the bool[]?
Linq.Where(GameObject.Find...(genAroundTag), tt => ...).ToArray(); ... where the rest of the code is as i didnt want to type it out
yeah, i can't find that ICollection.Where that returns bool[] in the C# docs
Thanks
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)
usually these games use a component on their UGUI-like canvas
can y'all help me with this script (i've done walking part, now i need help with jumping)
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?
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?
So basically i should be doing this on my Canvas and somehow track the position of the object?
yes which is pretty straightforward
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!
a powerful website for storing and sharing text and code snippets. completely free and open source.
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!
If you're pretty new to coding I'd checkout and ask in #💻┃code-beginner
Start from addressing the errors in your console. It's likely that they're causing some of the issues.
Maybe start from explaining what library exactly are you trying to get working..?
use an asset store package
there ar efree ones for sqlite
there is probably also a github package
Mono.Data.Sqlite
Ok, and what are the errors?
Sorry, had to pop out. Will ask again tomorrow when I'm at the PC again for enough time. Sorry about that.
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?
Why are you dividing and scaling it?
It should map to your screen pos correctly without any additional math manipulations.
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
I'm not sure. What do you get from just WorldToScreenPoint?
U mean what value for screenPoint?
Yeah. Well, visually, how does it correspond to the world pos?
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
Take a screenshot of the scene view with the canvas visible and the image selected.
you mean like this?
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.
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
There's a whole velocity over time module
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
You're looking at start speed only
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"
Start speed is just that - the speed when the particles spawn
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
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. 
Of course the device hardware matters a ton
WebGL is no exception
Have the stars accelerating nicely with that, thanks @leaden ice.
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?
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
it has nothing to do with namespaces
unless you are simply not including the appropriate using directive.
The problem is your asset likely has an assembly definition file
I am including using NameSpace. In all other scripts it works, but not in asset I mentioned.
in general though you shouldn't be modifying asset code unless you have a really good reason
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.
I cant pass parameters to C#
What do you mean by this?
What parameters do you need to pass and why can't you pass them?
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.....
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.
Yes, but that would mean AvVideo pro will have all logic javascript, and another script will have parameters on it. How I can be sure that in javascript side the parameter javascript will be written before AvVdieo pro javascript? 50/50 chance is not of my liking.
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:
- pass data to JS
- initialize the AvVideoPro stuff
in that order
isnt JS compiled on build with all classes and stuff?
Well first JS is not compiled at all, but second what does when it is compiled have to do with anything?
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.
regardless
you control when the code executes, no?
and "placing js in a file" is not the same as compiling but I digress
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 😭
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
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!
Awesome, any books or articles to go along with it? I'm interested in snapshot testing, replays, etc as well
what do i have to do to make my scriptable pipeline visible in the project's pipeline picker?
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);
you sure you want to use Terrain here instead of just like a ProBuilder mesh?
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)
also why are you doing AddForceAtPosition and then using Vector3.forward as the position?
whats the variable
name
i was trying out the different
ah
i shouldnt use Vector3.forward?
Why are you not just using normal AddForce is what I mean
as a position to add force to the ball? Seems weird
yeah the interaction has nothing to do with how you're adding force
I was just commenting on it being very weird
Choose the correct ForceMode:
https://i.redd.it/6y8myu3ruxo71.png
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
How we fixed an issue like this years ago was 2 images on top of each other. 1 image fully visible for the user of your dog, 1 image invisible behind it which you colored in over the dog. So you made the head part of the dog fully red, aka 1, 0, 0, the ears fully blue aka 0, 0, 1 and you raycast on the colored image. You can check what color you actually hit.
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.
Yeah I'm looking into that! I just wasn't sure if I could force raycasting to pick up on an image layer that's invisible to the player.
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..
Just hide the layer that image is on of your camera, but do raycast against that layer.
Yeah, all I needed to know was that it was possible! I'm excited now c:
How do I calculate direction of enemy object from player, but only 4 basic direction( east, west, north, south) ??
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
Tnx....gonna try it
does it matter what scenes are open in unity when u build?
or only build order in build settings?
only in build settings
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
If you mean transparency, then select that image and check its format. It probably is a version without an alpha channel: https://docs.unity3d.com/ScriptReference/TextureFormat.html
If I use Instantiate(myScriptableObject) will I receive a shallow copy of the scriptable object?
i think its a deep copy
If you mean that if you Instantiate it 10 times and that it will point to the same one then no, of course not.
^
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)
if you just want the same one then don't instantiate it just use myScriptableObject
It's not the SO itself, it's the variables inside it that I want to clone
pretty sure it's going to deep copy and do new allocations
Yeah, every variable in a class will have its own value. Unless its static of course.
Just like the normal behaviour.
if you don't want that then you'll need to make your own cloning function for that SO
consider, though, that your 'runtime' versions of things may deviate from their 'config time' versions, so passing those properties into a similar but non SO class is often the way to go
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
How would that even work? I don't see any way to be honest, can you even do that with components?
like create a blank one from the type (though i think that'll still allocate for serialized fields) using CreateInstance(typeof(SOType));
https://docs.unity3d.com/ScriptReference/ScriptableObject.CreateInstance.html
and then set the references to the fields again
Ok thanks to everyone
Why UnityEngine.LayerMask is not marked serializable? It's an int..
Bc it's a bitmask, not an actual integer number . . .
You can serialize a Layer type, and use that as a mask.
uint could work too
Naughty attributes has a inspector thing for layers
https://dbrizov.github.io/na-docs/attributes/drawer_attributes/layer.html
Odin inspector probably does too, though i never used it
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
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?
What does the flag mean?
might be a bookmark
Thank you for answering. How do I get rid of it?
huh, maybe right click on it? I'm not using VS currently
Thanks. this was great: Ctrl+K
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?
Add an additional condition that the game must currently be paused/unpaused as appropriate
Hey everyone, I am trying to move a go but its child containing the sprite does not move with it. any idea?
Well, suppose I didn't stop the game. So instead of the pause menu, he wanted to open the player inventory. Then what path will I follow?
OK, I'll try. Thank you for your support.
does the following move the objects children as well?
transform.position = pathCreator.path.GetPointAtDistance(distanceTravelled, endOfPathInstruction);
moving a parent always moves the children unless another script or component counteracts said movement
for example dynamic Rigidbodies will overwrite any such movement
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);
}
What am I looking at here?
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)
you have that IsAssignableFrom backwards
Where(type => typeof(IEffectConfigData).IsAssignableFrom(type) && !type.IsInterface)
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])
This is the code that makes the tranform changes for the position
What is the question though?
ok but - as I said above, yes children will move with their parents under normal circumstances.
(Also !cs)
somehow, it worked. I dunno why. sorry if i wasted your time. and thank you
Lol all good
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?
that object doesn't have the GallerySelectorFrame component on it
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);
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
yes, [Serializable] on top of MyClass and then the variables inside can be serialized like usual
Or if you don't need to actually separate it for logic reason then if you have the Naughty Attributes package you can do:
https://dbrizov.github.io/na-docs/attributes/meta_attributes/foldout.html
Yeah but there is a dropdown menu if I do like that (I want to remove the "drop down" menu)
i thought you wanted that?
oh, so you want the opposite
uh, maybe with a custom inspector
it looks like you are doing a lot of editor tooling faff
what are you trying to do?
what is this all for?
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
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.
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();
hey guys
does anyone know if it's possible to do gpu instancing for animations while also keeping animation layers?
what do you mean?
this isn't sounding like a coding question yet. what is your objective?
last time i tried to reply to you you didn't really answer the questions
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
my objective is to have 1000 animated skinned meshes (or converted somehow) with different animations for different layers while also having a nice fps
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
okay, is this for some kind of battle simulator game?
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
yes, i also apologized later for that.
no, i'd prefer to not rely on an asset from the store
this is what every guide online i found said. have you used sqlite in unity yourself?
not trying to be combative, just genuinely curious. it seems like using sql in unity really shouldn't be that hard
here's an example: https://www.mongodb.com/developer/code-examples/csharp/saving-data-in-unity3d-using-sqlite/
but i actually did just find the solution, i missed a step to download a separate .dll and also add that to plugins folder
Code, content, tutorials, programs and community to enable developers of all skill levels on the MongoDB Data Platform. Join or follow us here to learn more!
thanks!
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?
The latter
Figured, thanks
Easiest way is probably to use a public static float and multiply that with the things that need to be modified
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();
}
yhea I'm most likely use a custom Time class instead of the default one, which I multiply with that public float
You're playing it over and over, causing it to restart without playing it out. Just a guess. No idea where that's getting called
On the onClick event of a button
I think I already know the culprit though
I'll
That didn't work, it's probably because I disable the gameObject afterwards, Ig I'll just turn of the rendered instead, that should fix it
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.
Problem, how can I just disable the renderer? Do I have to get all the renderers from the children from the parent?
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
I'd probably have to restructure a lot of code if I want to do it that way 
Would it be bad to just move out of the screen?
if that is the case then your code is probably too reliant on where an object exists in the hierarchy
No, every object is in charge of itself
There's no main controller
you don't need any sort of "main controller" to be able to have the audio source separate from the renderer and stuff
Well they'd have to reference to an object besides itself
so?
Which that'd be a "main controller" of sorts, since all point towards it
no . . . it would simply be a reference
no it's not
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 ...
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

all of these things work regardless of scene
and yes the scene needs to have been loaded first naturally
These methods are quite slow though
using a singleton would be faster
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?
you have to adjust its settings
https://docs.unity3d.com/Manual/class-AudioSource.html
Yes, as long as the source has 3D sound enabled (not a code issue)
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
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
but how can I check and see if a certain sound effect is playing from only one audio source at a time?
why?
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
Why not attach a source to the zombie?
of a specific type?
using the existing unity audio tools
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
anyways more on this, i am, i'm passing it in to the manager so that the manager uses it, but when i check to see if a sound of a certain type is playing, i don't know how to check every single possible source.
or if that's even what i'd want to do
oh shit hang on i have an idea
if that doesn't work, thank you for telling me about this, i'll be sure to use it.
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
oh ok
i'm not sure
i just found out that PlayClipAtPoint is a thing and that's basically exactly what i need lol
📃 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.
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
It seems like you don't want to be using a database if you aren't putting the information directly into a table?
you'd have to explain a lot more about what you're trying to do:
- What kind of data is this?
- What is the data associated with? (a particular user? A particular match? A particular virtual object?)
- What kind of database are we talking about?
- Do you want structured data or just a binary blob?
- What kind of access patterns will you have?
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
Oh well, good thing you want to change that
BinaryFormatter is insecure and opens vulnerabilities for your app, it should not be used anymore
yep but is a proto, btw I quit friday but need to figure how to save that files on db without throw everything
some help? any advice?
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)
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)
The computer that has the MySQL server, is it local or remote?
You'll also have to download and install a MySQL connector library, so you can query directly from the code.
I found this: https://www.mono-project.com/docs/database-access/providers/mysql/
Not sure if it's still maintained though. Unity doesn't make things easy when it comes to third-party libraries
at the moment is local, but in the wet dreams of my boss it would be a server
thanks i ll read that
On a server you'd basically want an API to interface the database, so you can add validation, auth and various other security checks
If this is really your ultimate goal, having Unity talking directly to the database is not going to be feasible
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
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.
IState is an interface he created
But yours are white because your IDE is not configured
You need to configure Visual Studio to work with Unity properly
!ide
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.
Well it turns out I just had to restart visual studio xd I checked and everything was installed etc.
somehow the unity api wasn't connected to vs
thank you :)
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.
As per the docs for triangleIndex, it only works for MeshColliders
not for any other kind of collider
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 ?
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
Sure I’ll send a screenshot of the code in a minute
No screenshots please
Post code according to the !code guidelines
📃 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.
Consider "large" as greater than 20 lines
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.
Vector3 projectedForward = Vector3.ProjectOnPlane(player.forward);
camera.rotation = Quaternion.LookRotation(projectedForward, Vector3.up);```
was there a way to change the #define of a shader from a script?
I think this does the opposite of what I'm asking...? It will take only the y rotation of the player and ignore everything else. I need to ignore only the player's local y but take the rest.
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
)
);
Hey, is it possible to clone a gameobject that is not a (PREFAB) ?
meaning it's already a clone in the scene
Yes, Instantiate it
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.
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?
ok cool , thanks a lot 🙂
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.
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;
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.
what is this
what are you trying to do
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
what are you trying to do?
I just talked to a friend and think I have an idea to fix my issue. If not I'll be back.
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.
yes, but why
what is this for?
what is the y of your xy problem
(you don't need the null-ref static field anymore, just assign null or default in the constructor)
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
Yeah ngl this seems wonky, the mix of regular interface implementations and explicit ones does not help
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.
okay...
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
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.
They type of game is pretty irrelevant.
hmm...
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
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.
Okay? This makes complete sense to me, I just needed to know how to use make a null struct.
what are you trying to do?
i think if i polled all the senior unity developers i know, they would pretty much agree, without a doubt, that what you're doing doesn't really make sense
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
Wou I am busy I am not ignoring you
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)
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.
Also to be fair IoC hasn't made it's way into game development as for the majority of situations it isn't worth the time and complexity.
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.
I would be interested in knowing what you are thinking, and why that type of game specifically you saw this as being used in?
I am making is a simple point and click... work out the kinks(and this is way over kill for)
well whom is this for? what is the idea?
are you making a library? for whom or for what?
_decorator = default(Handle);
Ah like that. Yeah that makes more sense.
I was going off of what Unity did for PlayableHandle class, and now not sure why they did that?
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.
My future game I want to make is a multi player game
okay, so you want to make a networked, realtime multiplayer FPS in unity
that is your goal?
more or less yeah.
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
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.
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
Fair, having faced problems with the lack of multithreaded/async support already on other projects.
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
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.
unity already has SendMessage and BroadcastMessage. there's also unirx
and FindObjectOfType
for "service discovery"
it has all this stuff
Have used unirx and wasn't a fan, like wise for the SendMessage and BroadcastMessage have always been clunky to me. Good DI also should make life much easier than that(coming from .net side of stuff), and decouple code rather than couple it more, where the stuff in unity ultimately couples it more.
Anyways I have to go, though thank you again for the feedback.
Would anyone happen to know what could be causing this error?
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;
}
}
there is already a Unity Defined CharacterController class, no?
what do you think is wrong with it? what's the issue?
I figured it out.
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
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?
On the Sprite Renderer Component => Color => Change alpha
already done that but doesnt work
what's a more condensed way to write this, without linq?
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.
Does anyone know where Texture2D.EncodeToPng() went? I'm using 2021.3.16f1 :/
thanks, i'll have to find a way to obtain that because as it stands i dont have that namespace
Seems to be in this module:
https://docs.unity3d.com/ScriptReference/UnityEngine.ImageConversionModule.html
cant seem to find it 😦
Oh, I found it!!
Thanks!
man, they really over-complicated that one!
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
I think it should be included by default.🤔
Did you upgrade from an older version perhaps?
Nope, not at all
this is a fresh project
Weird. But oh well.🤷♂️
is mouse Input.GetAxis the delta of the last frame or the last call?
ah yeah, weird i missed that, I always do that.
there
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
Pretty sure that's Linq though🤔
Of the last frame. I've yet to see unity API that returns different values from last call.
ForEach is not Linq 😉
However it shares downside of Linq, slower than foreach and closure allocation
Could do h.dirty |= h.hull == null if you want shortcoding
But what are you trying to do
check alpha is transparency in the import options?
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.
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 ...
already did but doesn't work
Hello
How do you make a svg file from a string and upload it to a spriterenderer?
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
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
Do you mean Mathf?
Ye
Google: "how do i declare a list of tuples C#" it will tell you everything about it.
its not actually showing me how to declare one
This is the first answer for me in google.
all it showed for me was Tuple Deconstruction
How do I check if a point is on a line from a to b given a thickness variable?
What part of the declaration isn't in this example? You could just omit the data if you want.
is it a straight line?
because u could use gradients
for now yes
SphereCast from A to B and check if the start of the line is hit and the end of the line is hit.
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
Can you explain how you would find out weather the point is on the line using a sphere cast?
make a bunch of balls
Well the sphere cast wouldn't hit the check this, so it's not in the line from a to b.
this only works if a point is exactly in the line
to make it simple just use colliders
oh so you mean I draw a box from a to b and check if [CheckThis] is inside it?
oh I thought this would reaturn some bury result
so what I understand you are basically making a mathematical function with k*x?
i dont know what its called in english because i didnt study in an english school but i think it was smth like
y = mx + c
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?
you think this is a valid aproach?
Hey gang, would anyone have a minute to help me with some strangeness regarding SetTemplateCustomValue and WebGL templates?
sorry i had to do smth
you can check
whether BC is parallel to AB
if it is
then C is in the line AB
unless its behind B
yes that is actually what I was trying to do here
idk abt the width part tho
@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
Yes i m trying to make one
Its basically a capsule check
if ur struggling why not just use triggers?
Triggers?
colliders
I'm trying to make a shader..
You dont always want gameobjects and components for calculations like this
u never told me that tho
its the easiest way to do it. Not the most efficient tho
ye sry
yea idk anything abt shaders
It s just math
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
yes that makes sense I'll just have to find out what NearestPointOnLine does on it s inside
Just yoink one from here
(You want the finite version)
Ye thank to both of you
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));
}
Capitalize that k in key
ohh
And set up your ide
im using vscode for a little bit
https://www.youtube.com/watch?v=R7aVLRUl-z0 what do i need to learn for making like this football dribble system
Procedural running / dribbling soccer ball in Unity in C#.
its temporary
i think inverse kinematics and blend trees
That’s a very advanced thing. Basically everything relating to animation and character control
there is no single right way to do it and it depends a lot on the specific game
hmm got it thanks
works suprisingly well
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
}
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.
Oh , I can use the time in the function which is the third parameter. 😛
this is the line causing it
GameObject new_room = Instantiate(roomObject, pos * distance, Quaternion.identity);
roomObject is not mentioned anywhere else
show where it's declared
wait, it's saying it's not assigned
so, where is it supposed to be assigned?
It clearly is not
Make sure that it is assigned and that a prefab overrides its values, should you use that
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?
Is update of fixed update the one that is going to have the same time for every device?
FixedUpdate is 50 times per second by default on all devices afaik. There might be a difference in phones that are 30 FPS maxed, don't know what the FixedUpdate will do then.
Not sure what you are trying to achieve, but you can make Update framerate independent too.
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.
you just need to multiply your timer with Time.deltaTime in Update
Alright. Got it thank you
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/
There is a reason even AAA games say do not turn off power while saving indicator is on. All you can is a timed autosave a minute before they kill the power. If they do it at a reliable time, or just autosave every 5 mins and hope for the best
You can also keep the last save so have a autosave and a autosave_old and fallback to the old if latest is bad
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
how would I detect if data is "bad"?
you cant do anything about that exept dont overwrite the previous successful save
that depends very much on how you save it. I would do a hash of the data once my write has finished and save that as well. Then when I read the data back I can check if its hash matches the stored one
apologies, I'm not too experienced with data writing. what does it mean to "do a hash of the data"?
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
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?
yes
you can put the checksum at the end of the file, or the begining
or even have it be the filename
gotcha
not sure what you mean, but have you used the rigidbody constraints in the inspector?
var rot = Quaternion.FromToRotation(transform.up, Vector3.up);
rb.AddTorque(transform.forward * new Vector3(rot.x, rot.y, rot.z).x * TiltSpeed);
do i ask here for help ?
If the problem is code related and somewhat of an intermediate level.
well basically i wanna implement a system but i can't figure out howww
Go ahead then.
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;
}
}
Does it need physics involved?
wdym ? ( im kinda new so xD )
if you mean falling and gravity then ye
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?
Okay. Then I don't understand.
Your movement needs to both move to a point you click and be affected by gravity?
Does it not need to reach the target point?
ok so let's for example I want to make it like that , where you click and like pull the ball i guess , and it moves to that direction based on how far you pulled the line ( there should be a limit for the line ofc )
just in terms of best practice, should i handle sensatory checks from an ai in a behaviour tree, or elsewhere?
It moves in that direction? Not exactly to the point where you pulled it to?
yup
Ok, so you've got the movement part working. Is it just the scaling of velocity based on the drag distance that you miss?
true
also the draging system
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.
cant you just get the distance between the pointer and ball then apply the distance value on the "rb.velocity = dashDirection * dashSpeed;"
ok nvm i got this working so nvm this
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
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?
Check the distance between it and your destination is small enough
if the path has a distance property then you could compare it with distanceTravelled
Hi I tried creating a custom material but it turns into pink
I already set the Scriptable Render Pipeline Settings to URP
You are using the Standard shader which is not a URP shader
hence the pink
it's not compatible with URP
Also this is not a code question at all, you're in the wrong channel
oh sorry
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
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 :)
isn't that really bad for performance?
my team project is the simplest mini-game u can ever imagine, yet i was asked to create some hardest system for it
lmao
Hashing is really fast Im not sure what you mean. Its not like he will be doing it every frame
the team lead wants to use hard systems to compensate the blank mini game nature of it
Haha, I get where you're coming from
I'm making a 2D shooter and I'm really pushing what I actually want out of what would otherwise be a simple project
huh, not sure what I was thinking of then
Good talk😀
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
Uhhh can you name specifically what you are trying to reference? Not sure what you mean exactly
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
Can you be more specific?
Namespaces are generally not an issue at all.
Assemblies can be for sure
Are you trying to make changes to unity's code or something?
No just to an asset from unity's store
generally you should try to avoid making changes to them
i think i will break the system to small steps first
especially since now if you want to create a backreference from their assembly to your assembly you will end up with a circular dependency
guys how to get current time? the time obtained must not be affected by timezone and devices, because this app will be used by ppl from few different countries
the asset im using is using default raycasts but they dont work in Physics Scenes (i need them for the sake of my project)
so i kinda have to edit it (and replace default raycasts with PhysicsScene.Raycast)
Time.deltatime nah ijk tbh i also wanna know how to do that but im dum
im so dead rn
Ik lol ijk but srsly tho.. how would you do that
Pov: its 11 pm and you have class tmrw
What asset are you using
??
I would say rather than creating references to your code specifically, edit the package code to take in whatever parameters you need insteead
such as the physics scene
then you won't have any assembly issue
Just use the server time. You care about how much time has passed not what exact time it is.
u mean my team's server, but its not C# lol
ok i will keep a look at it
wait i found something like datetime
Well if you check time on a users device they can manipulate that
maybe it will help
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
Why can't you create the physics scene outside and pass it in? Aren't you already creating it outside?
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
oh i think I can..
ok thx👍
Heyo
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 :)
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)
Using strings is a bad practice. But you could make a custom editor that would serialize your attachment types and make them visible in the inspector
an enum is a simple way, but you'd only edit/change the enum if you create a new type of attachment, not a new attachment . . .
I see what you are saying, although I will likely not, for example, have every attachment of type scope accessible on every weapon
Which would result in a very long enum
just add to each item like
enum thingytype
{
scope
clip
rail
etc
}
when when seeing you can just check the type
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
a more advanced way is to use SO enums, this way you don't need to edit an enum if you want to add a different type. you'd create a new SO asset that represents a type of attachment. these SOs will be used like an enum field . . .
It's possible to set things up with SOs you'd keep the set of SOs for different attachment per gun.
(if you don't want each type of scope for each weapon) just have like scope/reddot/holosight for enums
I mean yes...but easier to just be a tiny bit more detailed in your enum
I dislike enums with how its so easily breaks with serialization so I almost always go for SOs in such setups.
I mean, if you need to add another item to enum just put at end
then it doesn't break serialization
And then you are more people working on the project adding at the same time and bam you have bad enums all over the place^^
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 :)
@thick socket for this reason i like to use SO enums to avoid the hassle. it is a different approach though . . .
how would that look like?
main reason I use enum is so it will autofill and I don't have to worry about typos with something like strings
For sure! For things that are by nature unchanged like directions, states etc I would go for enums. But for something that should be extendable enums has always been a pain to work with in non-solo projects^^
how would you do that for SO? not sure how that would work exactly
unless you are using Strings...which I don't like cause typos
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 . . .
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
but its like a SO with a list of strings?
or what would actually be on the SO?
You don't handle animation when its no input
no, the SO represents one of the values of the enum. from your example earlier, you'd have an SO asset named Scope, Clip, Rail, etc. . . .
how
ah, so you would have a SO for each type of enum
i didnt understand
why not just 1 SO with 10 Lists? (each named 1 of the values)
when both xDirection and zDirection are 0 you are not calling HandleIdleAnimation or HandleAnimation
curious if its just cause SO get laggy after awhile or if another reason
Well, one of the possibilities is because you're not comparing floats the right way. https://docs.unity3d.com/ScriptReference/Mathf.Approximately.html
So fix that first
how can i correctly parse a character of a number into the number its displaying`?
Not sure what you mean here?
As example this is what I would do in your case:
WeaponDefinition : SO
- List<AttachmentDefinition> allowedAttachements
AttachmentDefinition : SO
Create instances for all different attachments and weapons in inspector as assets, and add them in inspector as allowed.
float.TryParse or int.TryParse depending on what you are trying to do
nice. thanks
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)
this seems pointless
If feels like I can't leave them all as bullets with an enum if I want different types for pooling?
why not just do:
public class Bullet : MonoBehaviour {
public float speed;
}```
And set the speed in the inspector
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?
essentially skip what
do you just not wait at all
it waits for one frame
good enough
Was thinking it would be easier to do it this way so I can have pools of FireBall/FireBolt since they will have different animations/sprites
thanks
if you want to wait for one frame just do yield return null;
no need to use what you have
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?
just make two prefabs
no need to make separate scripts
You can just do yield return null
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
there is an implicit conversion between them, you don't have to do much of anything
My input would be to split the behavior of bullet to how it is moving^^ Bullet would be the final prefab name everything else is just component behavior.
i'm not using it in the way you'd use yield return null
if you want to not wait at all when it's 0 you can use an if statement:
if (waitTime > 0) {
yield return new WaitForSeconds(waitTime);
}```
wont I just have a pool of "bullets" so both the firebolts and fireballs would be inside the same pool then?
You will have whatever you set up
make two pools, and you will have two pools
i'll look into that
So what does that mean?
it means you can just assign float2 variables to Vector2 values and vice versa
assuming you mean Unity.Mathematics.float2
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?
it makes it slightly slower yes
probably not enough for you to notice
gotcha thanks
You should choose extendibility and readability over those nano-optimisations
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
Do compute shaders only use RWTexture2D as data to read from and write to with a C# script?
You can use general purpose buffers too. RWStructuredBuffer<WhateverStructYouWant>
RWTexture2D is specifically a texture
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
just make a Dictionary<ProjectileType, ObjectPool<Bullet>> pools;
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?
sounds like maybe your materials or something else is misconfigured
so wouldn't it just be:
Bullet CreateProjectile(ProjectileType pType) {
return pools[pType].GetObject();
}``` or however the pool works
from what Im watching from Jason Weimann, pools take like 3 funcs
one for making new item when there isn't one
retrieving it and returning it
one example i have is for a gun. most people use an enum for switching fire modes: auto, burst, single. i have an SO for each fire mode and switch between each fire mode SO when pressed. the SO does all the firing and bullet instantiating (pooling) based on its fire mode. this is a more advanced example though . . .
I am using a vector2 field here in the inspector, how would I change the Y label to say Z instead
you can't use Vector2Field
you have to create your own
I don't quite follow what you mean by this then?
how do I create my own
I was just taking your example from above and adapting it
inside the "create" function dont I need to return the item and instantiate a new one?
ah, yes
sure
👍
really you'd use a lambda
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);
so you'd make a ObjectPool<Bullet> CreatePool(ProjectileType pType) function that creates a pool for a specific type
yeah
could I just copy and paste stuff from whats happening inside vector2field cos I cant get the widths and stuff right
and it would do that with the lambda
where would I even find what EditorGUILayout.Vector2Field(); is doing
what is this error?, im trying to fix this for 2 hours but nothing works
you have compiler errors and/or your scirpt name doesn't match your class name
public Dictionary<BulletTypes, ObjectPool<Bullet>> bulletPools;
public Dictionary<BulletTypes, Bullet> bulletPrefabs;
is there a way to set the 2nd dictionary in inspector?
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 . . .
found the error, just because the score wouldnt add up by 1 the whole game broke
how could I set these prefabs in inspector? Don't see how to do it with NaughtyInspector...however I'm super new to it also
Google didn't give an answer sadly
Give your Bullet script a ProjectileType field
and just make a List or array of those
then loop through them in Awake to create the dictionary
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.
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
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?
which is line 23?
bulletPools.Add(bullet.bulletType, tmpPool);
sorry tried to toss the comment in to say which was line23 😄
did you initialize or assign bulletPools to anything?
hmm, yeah I didn't do that thanks!
whenever you get a null ref just check if each reference type variable on the line is assigned. easy peasy . . .
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
You can't define an array like that in shaders. You must specify a fixed length. If you want dynamic length, you have to use a ComputeBuffer, but those can't be referenced inside structs, same as textures.
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?
you wait 0.15 twice: once at the end and again before you instantiate. the first shot only waits once, at the beginning . . .
right
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
what happens if you remove the 2nd wait?
shoots super fast again...I imagine it must be after just 0.15f
however my animation says it only takes 0.3f to finish?
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 . . .
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
huh, didn't know that was a thing
i could try and look into that
Visual studio is using basically no RAM and doesnt tax the CPU at all
seems like if I do it this way I'll have to create a script whos entire point is to call the spawn function from a parent class?
the animation event can only call a method from a script attached to the GameObject with the animation. if you need to call a method from another GameObject, then yes, you create a proxy script with a method the animation event will call and that method will call the actual method you need to call on a different GameObject . . .
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?
fair enough thanks