#archived-code-general
1 messages · Page 78 of 1
some languages (C# included, in unsafe contexts!) let you know exactly where a thing is in memory
that location is stored in a "pointer" (it points to something!)
no point in getting into that rn tbh
can I not put a MonoBehaviour on an obj, if the MonoBehaviour is inside a Package ?
the main idea is, in C# functions can be put into variables
it's very convenient for allowing flexible behavior
you can pass a function that compares things into a sort function
and bam, you can sort a list however you'd like
yep
If i set my raycast on one object and decide which object the pointer should interact with, its not going to stop interacting with the other objects because i have canvasses on Top of each other
ah, so you have several unrelated canvases
yeah
perhaps you can have the first canvas say "didn't get anything" to the second canvas
which then tries its own raycast
private EnemyManager EnemyManager => EnemyManager.Instance;
is this same with assigning in awake or is it happening before awake
thats gona create spaghetti code whenever i have to add more content
I need to find a better way. But thanks for the help!
Very technical. I don't really think I understand to be honest. I got the help I needed though, so thanks
not if you keep it reasonably organized
actually, I guess I'd do it like this:
have a single input controller component
it is the only thing that listens to mouse input
it has a list of places to try that input in
it tries them in sequence until one of them says it did something
The thing is that these other canvas have buttons that listen for the input independently
It would be nice to have this Just Work without any explicit orchestration
but I dunno what to do about several canvases
yeah the technical stuff isn't important rn
You'll get there in time :p
there are 2 different things to do with 1 click in the same screen position
ah, so you might need to allow for multiple canvases to respond, just not some combinations of canvases
I got a screen space object that is on top of my world space object
The screen object has buttons that i use to select what thing is going to move in my world space object, and the click on my world space object decides where its going to move
I basically need my screen space canvas to block my world space canvas. and im doing so by setting the blocking mask to the collision layer i set my screen space canvas
but somehow it isnt working
Aren't all of these problems solved automatically if you just use the event system callbacks for everything? E.g. IPointerClickHandler
I think you can use layer order for this, I could be wrong
Sorry I think it’s actually called “Draw Order” for a canvas
i have to search about it
“UI elements in the Canvas are drawn in the same order they appear in the Hierarchy. The first child is drawn first, the second child next, and so on. If two UI elements overlap, the later one will appear on top of the earlier one.”
You're not assigning anything. The property in this case points to Enemy.Instance when you call it. It's the same as calling Enemy.Instance manually, but IMO this is cleaner and more scalable.
sure, but the problem is in multiple canvas
You can even do this, and store a reference to the instance in a field if it does not exist yet.
private EnemyManager _enemyManager = null;
private EnemyManager EnemyManager {
get {
this._enemyManager ??= EnemyManager.Instance;
return this._enemyManager;
}};
void Update()
{
this.EnemyManager.CanAttackPlayer();
}
Not that it matters here
Then as long as sorting order for the overlay is 0, it’ll always render before the other, also in the hierarchy make sure the canvas you want on top is higher up on the hierarchy
it is not a draw problem. Its a problem where my mouse click interacts with the multiple canvas where i only want it to interact with the object that is on top
private EnemyManager _enemyManager => EnemyManager.Instance;
without that => EnemyManager.Instance _enemyManager will be null so we are assigning did i understand wrong
im making skeleton like this
public class EnemyManager : MonoBehaviour
{
private static EnemyManager _instance;
public static EnemyManager Instance
{
get { return _instance; }
private set { _instance = value; }
}
private void Awake()
{
if (Instance == null)
{
Instance = this;
return;
}
Destroy(gameObject);
}
Just write a script that disables the GUI you don’t want to use till some condition is met
i have to have them enabled at all times
Then I think it’s a design issue
private EnemyManager _enemyManager => EnemyManager.Instance; is the same as private EnemyManager _enemyManager { get { return EnemyManager.Instance; }}
But the code you're sharing is the actual assignment of Instance. It should not be relevant to my message.
Are you saying you need the buttons to work or just be visible?
the canvas on the bottom is just an Image. The canvas on top has buttons. They both need to be visible all the time because the image is my map
Whenever i click on the map, it moves a certain object to that position
Then put them on the same canvas?
i cannot dude

one is screen space the other has to be world space
and have different sorting layers and all
im sorry i didnt understand exactly because i dont know much about getter setters
what is the diffrence between this two
private EnemyManager _enemyManager { get { return EnemyManager.Instance; }}
private EnemyManager _enemyManager;
private void Awake()
{
_enemyManager = EnemyManager.Instance;
}
none ever disappears
Top one is a property, bottom one is a field that you're assigning to
A property does not hold a value, it gets it from something else
If you define a property without an explicit getter, it's retrieved from something called a backing field
You're defining it to fetch it from EnemyManager.Instance
So the thing with properties is that you're not setting it in Awake, which prevents race conditions, which in turn is bad
Okay, you just want them to both be interactable and they aren’t? Forgive me if I’m not understanding the issue.
oh i got it, thank you very much
And you’ve tested that there is no callback working on one of them?
They are both interactable. I want that whenever i click on a button it doesnt run the functionality that does whenever i just click on the map
i want my screen space UI objects to block the mouse click event from reaching my world space canvas
I understand now
I think that is fairly easy, you just create a bool that gets set to true when you click on the screen space GUI, then you query for that every time on the world space GUI, or you check which UI your pointer selects first and ignore interactions thereafter
the bool doesnt work because if i set it to true after i click the screen space object then the functionality will run on world space anyway
PointerEnterEvent
Managed to make it work like this ```c
private bool IsPointerOverUIObject()
{
PointerEventData pointerEventData = new PointerEventData(EventSystem.current);
pointerEventData.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
List<RaycastResult> results = new List<RaycastResult>();
EventSystem.current.RaycastAll(pointerEventData, results);
return results.Count > 0;
}
I run this whenever i get Input.GetMousebuttonDown
Don’t do it then, use it on enter
If it’s on the screen GUI then you just want to disable the pointer events on the world level
ill discuss with the team which design option would be better
Thanks the help tho!
How can I make it such that A prefab has itself as a variable in a script, but when I instantiate it, it remains the one in the prefab and doesn't go to the instance?
I think you’ll be hard pressed to find a cleaner solution when layering GUI, it’s often a lot easier to just know where your pointer is at all times, rather than just on click.
If you are instantiating it, it means it’s going into the instance, can you elaborate the need?
I need to be able to refrence the prefab an isntance is an instance of
Reassign it after spawning
Instantiate returns the object you instantiated
public MyScript prefab;
void Spawn() {
MyScript instance = Instantiate(prefab);
instance.prefabRef = prefab;
}```
do I need a separate var for each thing Im instantiating where I need this????
Not if you just relegate this behavior to a dedicated component on the prefabs and put that component on everything
well I mean the spawner
the spawner would need a different variable to assign to everything at runtime
Use a list
Something like
waiit hold on maybe
someList.Add(Instantiate(somePrefab));
because It doesn't change in the prefab, so I can reference the prefab to set the referecne to the prefab
ok
hold on
Hatebin
Been looking through the docs and I cannot find whatsoever how the input is connected to the eventsystem, other than a base input module which I have no idea how that actually connects to my controller. I've been having a bug where my eventsystem is not updating to any new input modules simply because i do not know how to update it. Is there any way in the new input system to manually connect a controller to an input system? Thanks
this is also in the 2019.3 docs but... im using 2020.3 and there is no base input module?
Which input are you looking for,
Controller
So if you are looking for just generic input, you can use the input package, however I’d recommend looking for SAMYAMS inputsystem guide
No, I have the actual input down. Unity just does some backend stuff to connect the input to the eventsystem for UI. I want to manually connect an input device to the eventSystem.
in the docs ive found, there is a base input module but that turns into a legacy input module in 2020.3 (the version im using). Thus leaving me with no where to find how to event system finds the input device.
Ok so now im thinking its the playerInput.uiInputModule
nope not really related
NEVER MIND IM FUCKING STUPID There is a nice little dif between "Event System" and "UI INPUT MODULE"....
Also notably this is something you could easily code yourself either way
I am working on a VR game and I want a menu to spawn in front of the player. I got the code to place a model (book) always in front of my face. Now I need to rotate it so it faces me, any idea how I would do this?
Vector3 playerPos = playerHead.transform.position;
Vector3 playerDirection = playerHead.transform.forward;
Quaternion playerRotation = playerHead.transform.rotation;
Vector3 spawnPos = playerPos + playerDirection * spawnDistance;
instantiatedModel = Instantiate(model, spawnPos, playerRotation);
Currently it is facing outwards
Okay, I'll try it ty
Intantiate(model, spawnPos, Quaternion.LookRotation(-playerDirection));```
Thanks this works!
Yeah - seemed like world up was fine here - but if needed you can use playerHead.transform.up
is there a way to make it so that the in keyword prohibits value assigning on classes?
works for other types like int and float, but not for classes sadly
as in, setting the fields of a class?
yeah, that's a common surprise for any language with a "read only" modifier
it's really just no assignment
no - it's really for structs
damn
classes are passed by reference already
What are you trying to do?
You could always make a read only interface which the class implements and pass the object in as that type instead of its naked type
just pass in some values into a scriptable object which will be used later
hmm maybe a bit overkill for just value reading. idk i only use interfaces with things such as IDamageable and IPickupable so it's way out of my comfort zone
there's the alternative option
put a big mean comment that says you'll beat them up if they modify the object
that could work 😂
but yeah, if you read the feature specification
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-7.2/readonly-ref
it mentions that in was added to allow for structs to be passed by reference, but without allowing mutation
yea i read that, hence why im asking for a workaround
apparently c++ has what i need, but i dont do c++ so rip
actually now im curious, how would i do this?
Quick and dirty example:
https://hatebin.com/mfzqmnusro
Since void SomeMethod(IReadonlyPolygon polygon) { takes the interface as the parameter, it can only access things that are defined in the interface, such as the get-only property
hey all, lmk if theres a better channel to post this in: does anyone know of a store asset that you can use to generate graphs of nodes, like this map? ive tried using mapmagic2 which i thought would be cool as i could also use it to create fancy looking terrain, but im not able to get the spline (connection) data between the nodes (provinces) to use for the game logic
clarify: im looking for something that will let me generate procedural versions like this map, not just this map what i could build manually
ohhh that is really clever, thank you!
you should be able to use anything that can store or create splines
like the Unity Splines package
Although, I'm not sure what I'd do to decide on the exact shapes of the curves
It seems random as to whether they bend up or down
You just want the visuals, right? You aren't looking for something to actually store a graph of vertices (kingdoms/settlements) and edges (paths between them)?
how do I make a canvas element capture clicks, but not capture drags?
so, the if I click and drag, the element below captures the drag, if I click and release, it captures the click
no, the opposite. whats important for gameplay is the settlements + connections between them (ie i just need to know that settlement X is connected to settlement Y, not the exact path that is used to connect them), i need those in gameobjects/components for the gameplay. the terrain is just eyecandy. and i can manually recreate that map, but im really looking for something that allows me to procedurally generate a large variety of maps
so you need to figure out which settlements are neighbors?
hmmmm in a sense? its not just proximity, though, some settlements could be physically close to another but not have a connection
sorry ive been beating my head against mapmagic trying to get this result so im thinking in those terms
so you need to semi-randomly connect settlements together (without crossing the lines)
yeah. mapmagic2 does that part pretty well, i can have it scatter the settlements then pathfind and it generates a bunch of nice splines that connect the settlements in a satisfactory way... but then there doesnt seem to be anything in mm2 that actually outputs the splines, it just seems to be built to use them to draw textures on the terrain object, and i havent found a way of using the mm2 output to determine settlementX connects to settlementY
ahh, I gotcha
I would expect that to be possible..
Never heard of the package before.
its pretty neat, what you can do with procedural generation of terrain, and even putting objects on it, but the splines module looks... unfinished
i am trying to find documentation
actually, just noticed, the problem is not the button, its a textfield, because the textfield does capture drags. My text field however is non interactable, yet it still captures the clicks... hmm
I'll just dissable it
MMWG (http://u3d.as/oDY) wikis, issues, and most recent patches and betas. Plugin Tools are required along with this repository to make MapMagic...
yeye
playing around with it a couple years ago, i was actually able to get some quite interesting procedural terrain out of it, and changing the seed would generate entirely new maps at runtime, pretty cool
so that green scatter node is what scatters my provinces (which can be seen as little clusters of houses), and then it flows into that orange interlink node which generates a bunch of splines to connect those provinces, and then the latest thing ive been trying is the orange scatter node, which takes a list of splines and creates a list of locations which i then dump "PathPoints" on to (the orange dots you see in the scene)
but theres no way within mm2 that i have found to attach any other data to them. trying to think of a way to use them to generate logical X->Y connection information after the mm2 generation is done
and then got to that point and thought "dammit is there another asset that could do this easily" 🙂
30 years of software engineering and im lazy af, i dont want to write code, i want to ship games XD
i can increase the # of objects placed in the scatter node
but theres no way within mm2 that i have found to attach any other data to them. trying to think of a way to use them to generate logical X->Y connection information after the mm2 generation is done
I wouldn't try to do all that stuff inside MM itself
I would just use MM to generate the terrain and the provinces themselves (with Objects in MM as you have done there). I would then basically just take over with my own custom graph generation logic. Pretty much just check within a radius of each province to consider as "neighbor" provinces and then it's just standard graph logic from there
other than drawing the splines of course...
yeah i thought about that... but then i dont get the visual representation of the roads between the provinces, and that feels meh from a ux perspective
You get it... just not from MM
Use the Unity splines package or similar and draw the edges of the graph
hm
looking into unity splines, never used em before
can they be used to write onto the terrain?
As a crude first pass you can just draw them as straight lines with simple LineRenderers
I mean they're pretty much general purpose mathematical splines
theoretically you can do whatever you wish
there's no built in terrain drawing feature though
Is there a reason they need to actually be baked into the terrain?
rather than for example separate meshes laying on top
ah not neccessarily baked into terrain, but i would like a visual effect
mm2 just has all these super nice nodes for splines, like you can have it keep the splines to minimal elevations, so it naturally wraps around steep mountains and such
and a stamp node that flattens the ground around the spline so it looks natural
its just frustrating bc it seems like mm2 gets me 99% of the way there, and if i handroll my own pathfinding and generation, i'm having to write a bunch of stuff that mm2 does for me, just to get that last 1%
it would be very convenient to re-use the same paths, for sure
stupid question but are you using MapMagic 1 or 2?
MM2 has a splines thing
sorry if this has already been discussed
that's what's being used
ok tjhought so but wasn't sure
it sounds like the problem is extracting that data, so that the logical connections between settlements matches the physical connections that were generated
Did the mapmagic documentation website go down? I can't seem to find it
Perhaps a casualty of the war?
nevermind I see the gitlab link above
ok i genuinely thought for a moment that there was some kind of Holy War over map generators
i need to go lie down
yeah thats precisely the challenge im facing
Honestly I would email Denis Pahunov and ask him. I think it's probably exposed in the API somewhere but the documentation is sparse. his email is on his website https://www.denispahunov.com/
How can I get angle of clock arrow if I know it's forward vector?
Vector3.SignedAngle
oof
public static float SignedAngle(Vector3 from, Vector3 to, Vector3 axis)
{
float num1 = Vector3.Angle(from, to);
float num2 = (float) ((double) from.y * (double) to.z - (double) from.z * (double) to.y);
float num3 = (float) ((double) from.z * (double) to.x - (double) from.x * (double) to.z);
float num4 = (float) ((double) from.x * (double) to.y - (double) from.y * (double) to.x);
float num5 = Mathf.Sign((float) ((double) axis.x * (double) num2 + (double) axis.y * (double) num3 + (double) axis.z * (double) num4));
return num1 * num5;
}
what about it?
rather ugly implementation
Good thing there's no reason to ever even think about what's going on in there
eh, I have to copy it to assembly that is connected to Unity Engine 🥴
i c
There’s a render distance setting, it won’t render if the z plane of the camera is farther than this from a side of the decal.
you've become the biggest booster of unity splines
I'm just giddy they finally have the package. You know how long I had to recommend the Seb Lague package?
It’s been pretty nice to work with
....
What is a spline ? I tried googling it but i dont see how u could make a game out of it or how splines could help to make a game
you can't imagine how splines would be useful in a game? Really?
It’s a Lerp on crack
Here maybe this screenshot from the extremely popular city-builder game "Cities Skylines" will give you an idea
That is a phenomenal example!
I always think of turning the page of a book when I think of splines
Splines are polynomials between points, basically
rather than just straight lines
there are many flavors of spline
I prefer raspberry
Let’s be honest though, “Linear Interpolation” is the best combination of words of all time.
Oooh
It just sounds cool
Slerp time
I do love slerping 🍦
some kinds of splines also have smoothness guarantees
not only do the lines connect, but they also don't abruptly change direction
slurp
Scammed by png
I’m gunna have to learn splines at some point, but city builders gaming
this reminds me: I need to figure out how their grid system works
i have a vague idea for a game that would need to generate a city full of buildings
A game that generates buildings in a city?
Yes. It's going to be the Dark Souls of cities.
Lmao
Inb4 waveform collapse does it for you
well, speaking of that, lol
I've implemented that already
but I want to be able to place buildings along curved roads and, generally, get away from a perfect grid system
I love some waveform collapse, much less painful than A*
I started working on WFC with a sort of flexible world grid, then my brain fell out
i did it all in the ECS
what's up
it was very exciting
i screwed up rotations so many times. it is apparently impossible for me to imagine two tiles being rotated
I should probably move over, I’m starting to think default Unity might eventually struggle with my implementation over netcode
Not sure yet
Is ECS any good?
it's decently well documented now!
i found it approachable (as approachable as it can be, at least)
the tutorial series on building a bunch of tanks that drive around and shoot balls was extremely informative
Do u have to know all of DOTS or can u just use ecs
it's really incredible how attractive that game is
"DOTS" is an umbrella for a bunch of stuff
Ik what it is Job system burst compiler and ecs
the entity-component-system scheme is certainly the bulk of it
yeah, I already knew all about Jobs
i used them to run gradient ascent for an RTS game's AI, haha
Async programming scares me
although those jobs were synchronous
I learned all about async jobs with the ECS
it's very cool
you get to open the timeline and see tons of tasks running at once
insane performance
Yeah cus ECS uses structs instead of classes right
that's part of it, at least, yeah
a lot of stuff gets passed around by reference
it takes a lot of code
I think things are getting stable now? They completely changed how Transforms work at some point
I've seen some talks on it
maybe i'll give it another go during a game jam or something
make a horde shooter with 50,000 enemies
Are these game jams ever recorded ?
the last few I've done were run by my uni
there's one this weekend
i am sick, so I might try building a VR game at home
Where are they at ? I think there have been some in Austin Texas but ive never been able to attend
I'm gonna ask this again since it's way more active now:
Is there a way I can check if a urp decal projector is currently visible?
@potent sleet sorry, I should have specified better:
I need it to work with the render distance setting of the decal too.
Gave it a shot, thanks Praetor
use fadeScale in distance check
float distance = Vector3.Distance(mainCamera.transform.position, decalProjector.transform.position);
if (distance <= decalProjector.fadeScale)
{ // do stuff}
can you point me in a direction of finding a point on a box from a direction vector then? Because the render distance is not from the transform of the decal, but rather from the sides of the decal's 'box' that intersects with geometry.
thanks!
ok so, How can I have a NavAgent tied to multiple navsurfaces? because I'm having a bug where my chaser will stop chasing when I leave the surface it is on
are they connected ?
I know you can do Off Mesh Links between two chunks of the same surface
do you have multiple Nav Mesh Surface components?
yes
not sure on that one
Does that even work between two separate NavMeshSurface components?
it would make sense
it should
I've only ever done one big surface (since I've never had particularly huge levels)
cool, then yeah, you'll want off mesh links
2022+ now you need to place surfaces 😵💫
i like the new AI Navigation stuff
I use NavMeshes for sound propagation as well as navigation
yeah it was long overdue
this is basically the issue, the ball wont cross the blank zone
navmesh surface is great for enemies that walk on walls
well yeah
it's a gap..
would you need to make a separate surface for the wall?
yeah basically, then you select direction
ooh yeah, and you can animate them getting on and off the wall when they change surfaces
neat
but I can't predict exactly where a crossing will be, because the walls are oriented randomly, so then they would be able to get through walls I think
you could add off mesh links by checking that nothing's in the way
well its not fully random, its a layout with a random 90 degree orientation
yes you need to do a bunch of positional testing and whatnot
on runtime?
ok issue
the game is already barely above 35 fps
and that sounds very performace heavy
well, you'd do this just once
although a lot of the stress is from graphics
If you have an idea of where the joint is gonna be, then I would sample a random point in that area
yeah, I can do it in the same function as the generation
you probably have something else going on, this method is not expensive
then find the nearest edges of the two surfaces and do a raycast between them
or maybe overlap a box in that area
if it's clear, make a link
hmm
I could also try and condense the structures so there's some space where walls will never be and put it there
any tips on saving graphics performance?
I'm at a state where it looks nice, and I've already changed a bunch of settings
runs at 30fps usally
Use the profiler
post processing?
highly recommended read: https://resources.unity.com/games/performance-optimization-e-book-console-pc
yeah, although the game looks like crap without post processing
Maybe post the output in #💻┃unity-talk and folks will give you suggestions.
Output as in the profiler
ok I'll look deeper into the profiler
the offmesh links both broke the AI and made it zoom all over the place, and also it still didn't cross the gaps
then you didnt do it right
yeah
this is not correct id presume
I do take solace in the fact that my AI code was working perfectly, I just didn't set up the navmeshes right
I cant tell whats what
how are you setting offmesh link tho
if you're using Auto generate offmeshlinks you're gonna have problems
Oh
I just added this component and set the size to be a bit larger than the chunk size
nahh man u generate the map you gotta do it correctly via script
presuming I get the script working correctly, the off-mesh link should look like this? (Lets say theres no walls there)
does this define a cross-mesh area
sorry im being so asky
the width should be usually how much area within the link the Agent can move/cross
the 2 bigger cubes gizmos are StartPos and EndPos
right now they would go through middle spot to cross
I was reminded of something just now -- fuzz testing. You just...hammer the system with inputs for a long time and see if anything goes wrong.
Has anyone ever automated that in Unity?
I've used it to find quite a few bugs in Blender :p
i'm thinking it would be a good way to shake out any bugs in my UI system, for example, by mashing tons of inputs and trying to discover any weird edge-cases
all you'd need to do is enter play mode, then simulate a ton of random inputs
I’m trying to figure out how to make a enemy shoot a projectile in the directing the enemy is facing because it changes direction
In 3D - transform.forward
In 2D - transform.right or up
hey guys, running into a major issues here with Unity 2022.2.14f1, fresh install, installed the visual studio tools, but when opening the C# unity project in visual studio it says the project type is not supported. This set up is on my laptop which is only different from my desktop PC in that the laptop has Visual Studio 2022 professional, and my desktop PC has the 2022 Community edition of VS
I've tried all the common fixes like reinstalling, running a 'repair' of visual studio, etc. still have the same problem
Anyone know what I'm doing wrong?
I just have this
public class Keyboard : MonoBehaviour
{
private TouchScreenKeyboard keyboard;
public void OpenKeyboard()
{
keyboard = TouchScreenKeyboard.Open("", TouchScreenKeyboardType.NumberPad);
}
}
The OpenKeyboard() method get's called in the OnSelect event of an inputfield like in the image
No keyboard opens up though, I'm using Unity Remote 5 to test it
did you read the docs?
yes, I'm a little confused with their examples though
Not sure what all of these GUI.button() if statememts are about
I know, I'm testing this on my Samsung Phone with Unity Remote 5 App
Oh
so the only way to test if this works is to build the app and get in onto my phone?
I would guess so
make the APK
already on it 👍
how do I check if a rect transform has the mouse position?
I tried RectTransformUtility.RectangleContainsScreenPoint(rectTransform, Input.mousePosition)
also tried RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, Input.mousePosition, null, out _)
tried using Camera.Main
tried doing rectTransform.InverseTransformPoint (gives some huge numbers)
nvm got it
Camera.main.ScreenToWorldPoint(Input.mousePosition); Get's you the coords of the mouse
rectTransform.TransformPoint(rectTransform.rect.center);Get's you the transforms coords too I think
oh
:/
TransformPoint goes from local space to world space
InverseTransformPoint goes from world space to local space
@potent sleet I need some more help here if you can. Or anyone really.
I don't really know why this decal is appearing before the draw distance. I have this, which adds the distance (from the center of the bound (drawn in blue) to the edge of itself) to the render distance. I then check the distance from the camera's near clip plane (just camera's forward multiplied by the near clip plane distance in world space) to the center of the bound. Yet it's still slightly off, I don't know why.
Vector3 zPlanePos = Camera.main.transform.TransformPoint(Camera.main.transform.forward * Camera.main.nearClipPlane);
_bounds.IntersectRay(new Ray(_bounds.center, (zPlanePos - _bounds.center).normalized), out float distance);
float realDistance = (-1 * distance) + projector.drawDistance;
Debug.Log(realDistance);
Debug.Log(Vector3.Distance(zPlanePos, _bounds.center));
Yet the decal appears before the second debug log statement is equal to the realDistance.
(in the image I'm logging Vector3.Distance(zPlanePos, _bounds.center) > realDistance). It's true, yet the decal is shown. Also I am using the near clip plane of the camera instead of the player position because I could not figure out why the decal was appearing before the player got close. Using the near clip plane position makes it almost correct. almost.
does the behavior change if you change the near clip plane?
if not, then that's probably not relevant
no it doesnt. I forgot I could even change it to test, I barely touch the camera haha.
still can't figure out why it renders before the distance of the box from the center of the box + the render distance
also, I'm thinking of restructuring my entire game, again, and I could use a sanity check
Right now, each stat in my game -- health, stamina, mana, whatever -- is identified by an enum. This has already led to headaches, as seen in exhibit A:
I had the idea to make a ScriptableObject type that represents a stat. The type would hold localized strings for the name/description of the stat, plus the stat icon.
one issue I see that is that I'll need to do something like Resources.LoadAll to get a list of every stat
instead of just iterating over the values of the Stat enum
(i'll also be adding more kinds of stats, some of which are conceptually different from others. it'll be about as elaborate as Elden Ring/Nioh/etc.'s list of stats)
so those will probably need different types
I guess I should just give it a whirl and see how it feels. I'm still very early in development.
I have this script but when it runs the projectile does move.
📃 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.
please use a paste site
well how are you using the enum?
Here's an example.
swinging the sword costs 10 stamina, and deals 20 vitality + 10 stamina damage
so, in this case, I'd just be replacing the enum dropdown with a field that holds a Stat reference
One place that this seems like a win is localization: I'm doing some...suspicious stuff right now
private string StatKey
{
get
{
return System.Enum.GetName(typeof(Stat), stat);
}
}
this gets turned into a LocalizedString
actually, basically everything I do with enums feels suspicious
enums are funky little guys
tbh I like enums bc you can use it as a flag enum and use bitwise operators so you can easily say "this stat or this stat or this stat or this stat or this stat" in an if statement. I would even set up a method that I could use to take points away from multiple stats based on an int that represents the flag enum.
yeah, although I don't have it set up properly for that
since the enum values are just sequential
I am using enum flags like that in another place, where different interface elements are enabled depending on the current game state
I think the big hang-up is iterating over all of the stats
I guess I'd just make a static class that does a big Resources.LoadAll once
why do you need to iterate over all the stats with the current system?
any situation where I want to do something with every stat, like drawing them all to a status screen
and then it'd just have a nice static list of the stat SOs
it'd even sort them correctly so they show up in the order I want
rather than just "whatever order they have in the enum"
which is where the bitwise operators could come in. (make a method that separates out each field from an int value and performs a supplied action on the stat? Then you'd just need to call that method whenever you want to do something for certain stats, and pass a lambda expression to be ran on each stat.)
Well, are you concerned with performance or ease of use? bc you said you're in early development, so it's not a good idea to be concerned with performance right now, or so I've heard.
Ease of use generally wins.
Critically, it shouldn't feel gross to add and remove stats later
...which, lol
I am thinking about the potential cost, though
the big thing will be that I will look up stats with a SO reference, rather than an enum value
Hi, I'm facing a problem with my game, everything was going smoothly and all of a sudden i can't see the map, even by restarting the game
The maps shows up again when scaling the camera by 30*
I mean a for loop looping through even 100 stats wouldn't be too big of a performance impact in the big picture if you aren't doing computationally heavy actions each time.
lol
maybe you should make a static class and have that handle everything, so if you decide to switch back to enums later you only need to change it in one place rather than a bunch of places @heady iris
yup! And that way if you want enums it shouldn't be.. too hard.. hopefully.. to switch back.
what if you change the size of the box?
I'd fiddle with more variables
I wonder if it's accounting for how the box could be rotated
so that a corner is facing you
you'd need to add...a factor of sqrt(3)?
the render distance is definitely from the edge of the box to the camera. So if you stood in a spot and rotated the decal so a corner was within range, it would start rendering.
ah, okay
i give up on that tbh. I'm just gonna add a radius and manually control the fade and tell my team 2 bad lol
(they wanted it to work with the fade value on the projector)
I've had weird problems with decals, but not that one, at least :p
make your scene view 3D and check that when the camera is following the player that the tilemap is within the clipping planes of the camera?
Anyone have any suggestion in dealing with navmesh agent
isOnNavMesh returns true but
isStopped us causing error
can only be called on an active agent that has been placed on a NavMesh.
ah, one nuisance: this is going to work great for stuff like weapon scaling, since the weapon can have a list of stats that are used to determine its damage
...but it's inconvenient for things like health. An entity checks every update if it's at 0 health, and, if so, dies. But now it doesn't really know what "health" is.
It just has a bunch of stats.
stuff like "health" and "stamina" feel very different from things like "strength" and "reflexes"
they're numbers that go up and down all the time and have very concrete meanings
I guess I can just tell the entity what stat should be used for deciding if it's dead, etc.
that could certainly lead to interesting things like an enemy that only dies when it runs out of mana
Having an issue with Unity sort order--it seems that the sort order doesn't take effect unless I modify it after hitting play
I have a canvas at sort order 0, then a background sprite at 1, and text at 2. But at runtime the background sprite renders over the text. If I change the text sort order to 3 at runtime (or background to 0) then it works. But it has the same issue every time I rerun it
What is the best way to surround enemys around player
I have found one tutorial about that which has this script
private void MakeAgentsCircleTarget()
{
for (int i = 0; i < Units.Count; i++)
{
Units[i].MoveTo(new Vector3(
Target.position.x + RadiusAroundTarget * Mathf.Cos(2 * Mathf.PI * i / Units.Count),
Target.position.y,
Target.position.z + RadiusAroundTarget * Mathf.Sin(2 * Mathf.PI * i / Units.Count)
));
}
}
But problem in this if target is not accesable (out of navmesh area) enemys will go nuts.
or i can create waypoints around player and every enemy will check the closest and then move to that but this time there will be a lot of distance check which will bad for performance
can you suggest me bast way to achieve that
Hi! I have a need to send some web requests to initialise objects. I want to do it in a coroutine, but I need them to be executed in the order they are added, otherwise everything will break. Currently I have this:
There is ICoroutineTask interface with methods Start, Wait and Finish.
There is WebRequests class that generates ICoroutineTasks from a UnityWebRequest, with Start Wait and Finish with Wait being request.SendWebRequest().
The setting of local variables is done in Finish method
And finally the code for resolving the enqueued tasks is:
private IEnumerator WorkCoroutine()
{
while(_running)
{
if(_tasks.Count == 0)
{
yield return new WaitForSeconds(0.1f);
continue;
}
var task = _tasks.Dequeue();
Debug.Log("Dequeued task");
task.Start();
yield return task.DoWork();
task.Finish();
Debug.Log("Finished task");
}
}
But what I do does not work..
What is the correct way to do something like that?
Looks good to me. "Does not work" isn't enough to go off with, you have logs, you should say if you're getting them in the console. You can also place a breakpoint in there, and debug-step through the code line by line, inspecting the values as you go
Hey, Im very confused as to why putting the yield return null specifcaly there makes this last 0.6 seconds. Why does putting it at the end of the function for example make it transition instantly? Doesn't yield return null basically not do anything? Or at least thats what I though
IEnumerator solveFade()
{
float delta = 0;
float duration = 0.6f;
Color start = bgMesh.material.color;
while (delta < duration)
{
delta += Time.deltaTime;
yield return null;
bgMesh.material.color = Color.Lerp(start, "246F2A".Color(), delta / duration);
}
Module.HandlePass();
}
It makes it wait until the next frame. It's the shortest amount of time you can wait, because coroutines are updated at the same rate as Update.
yield return null waits 1 frame you should use waitforseconds realtime to wait 0.6seconds
Hi, I'm facing a problem with my game, everything was going smoothly and all of a sudden i can't see the map, even by restarting the game
The maps shows up again when scaling the camera by 30*, i tried changing the Z axis but it dont do anything
can some one help me I'm trying to create Jenga as an asset but as soon as i start the project the blocks fall is there a better way to do this i'm using physics in this example but the blocks slide all around not sure what to do can i get soeme hlep please
i don't think you're going to be able to create a game of jenga with unity physics
maybe if you crank the bounciness down and the friction up?
i dunno what constraints VRChat puts on you
i created a physic material and took off bounciness i might need to crank the friction up maybe that works
that actually worked thank you
just needed friction
Hello, Im working on a new movement system based off a tutorial. The system works fine but there are a few tweaks that need to be made, one of which is giving me a bit of trouble. When jumping (with current system) despite having no "air control" the players rotation is still able to change the direction of the in air velocity. I want to make it so that when in the air you are still able to look around but do so wont change your momentum.
Heres le code: https://hastebin.com/share/ididitupit.csharp
I should note that I've done a few tests without much success like the if statement at line 134, feel free to pretend that isn't there
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
my mind is gonna blow up
I had a property, with a getter and a setter. In the setter, I set the value of a privatefield, and I printed "Field set"
the private field was not accessed anywhere, only the getter and setter
and, for some weird ass reason, the private non serializable field is initialized to a default value
and it is a struct, not an object
without the setter being called
what in the world can be going on?
if the field was public, I get it can be assigned, because its a MonoBehaviour, but with a private field? it should be null
Hello, is there a way to create a assetbundle without using Unity ? For my app, I need to get a list of asset from a server, so I'd like a script that fetch files from a list, make an assetbundle with them, and return the result. I got some result using python but the result assetbundle is compressed, so when using UnityWebRequestAssetBundle.GetAssetBundle(), I get :
Error while downloading Asset Bundle: Failed to decompress data for the AssetBundle
Is there a simple way I'm missing here ?
does unity not allow any fields in a MonoBehaviour to be null?
you can have plenty of null fields
but
structs cannot be null
(barring using Nullable stuff)
it's like trying to have a null float, or a null int
If you have serialized non Monobehaviour fields Unity will create default instances
it is a value type, not a reference type
If they're not serialized they'll be null
meant a class yeah
If it was serialized in the past it might still set a value. Try changing the field name, just to be sure
okay, so it is a class
So yeah this
this is a non-serialized field
^
Oh sorry I butted in late here
its private, and I didnt specify for it to be serialized
also this behaviour stops happening and comes back again basically randomly
wich is even more weird
Shouldn't happen, but if you have an example feel free to show evidence
I could believe this. I've never looked at how unity behaves if you mark something non-serialized after it serializes a value for it
I ended up making a giantic botch, and setting a boolean to true when the variable is assigned using the property. The property only returns the object if that boolean is true, otherwise it returns null
It's not a static field is it?
no, not static, but its a singleton
so im assigning the MonoBehaviour to a static field
Can you show the code etc
its somewhat big and I cant seem to reproduce it standalone
because it happens randomly
I'd guess that something else in your code is causing it then
And it's obfuscated by the complexity of the code
but its a private field, and nothing changes it other than the property
and im not using reflection or anything like it
do you have any of this stuff set
well, unset, more importantly
i wonder if this is somehow tied to something not getting cleared when entering play mode
since you did say it's a singleton
I haven't touched them, but where are they?
Project Settings > Editor
They let you skip some steps while entering play mode (very nice for rapid iteration)
with the caveat that skipping the domain reload can cause some Funny Stuff
okay, so that's not it
like subscribing to a static event every single time the game runs, piling up more and more
for a sanity check, do you find any extra references if you shift+F12 the private field?
ctrl + F?
no, shift+F12 to find all references
(i think that's the shortcut in VS)
it finds every place in your code that references something
the opposite of F12, which takes you to where something is defined
ctrl + shift + F in rider
ahh, rider, gotcha
and nope, no references
even if I comment it out, the only lines that have an error are the property lines
could someone help me find out why this function isn't working properly? The debug.logs show non negative values correlating with the input, but the object this is attatched to doesn't change at all (iskinematic is off)
private void ApplyMovement()
{
Vector2 drift = new Vector2(movement.x, movement.y);
Vector3 velChange;
// Apply the drift and clamp the player's velocity to the maximum speed
Vector2 rbVelocity2d = new Vector2(rb.velocity.x, rb.velocity.y);
rbVelocity2d += drift * driftSpeed; //* Time.fixedDeltaTime;
rbVelocity2d = Vector2.ClampMagnitude(rbVelocity2d, maxSpeed);
// Apply drag to slow down the player's movement
//rbVelocity2d *= Mathf.Pow(1 - drag, Time.fixedDeltaTime);
//zVelocityChange *= Mathf.Pow(1 - drag, Time.fixedDeltaTime
//rb.velocity = new Vector3(rbVelocity2d.x, rbVelocity2d.y, zVelocityChange);
velChange = new Vector3(rbVelocity2d.x, rbVelocity2d.y, zVelocityChange);
velChange *= speed;
rb.AddForce(velChange, ForceMode.VelocityChange);
Debug.Log("rbvelocity: " + rbVelocity2d);
Debug.Log("rb . velocity: " + rb.velocity);
Debug.Log("drift: " + drift);
Debug.Log(movement);
}```
In the editor, there's this nice system for moving an object based on its center, which takes its childrens' position and scales into account. Is there any built-in way to do this through code, or should I make my own function for it?
you can just GetComponentsInChildren<Transform>() and average their positions, then calculate the move delta and add that to the parent's transform position
you mean moving localPosition?
no, world position
In this case I want the local position because I'm using a script that creates a bunch of 3d text objects, but they are centered at the bottom left, so I want to set their local position to make them centered around the parent object.
so yeah then do what anikki said
alright thx
get the mean position, calculate the shift, then apply the shift to the localpos
PlayerPrefs Sets "Variable" + ProductNumber | 1
// Player now owns Variable4 & Variable7
Array Products [10]
Instantiate All PlayerPrefs Variable_ that are 1
```What would the code be to do such thing that instantiates shop products that playerprefs only equal 1 to, using the count of how many are in the array from inspector you defy where the loop check ends??
idk if im having an ictus or that made no sense
If you are responding to me, it does make sense. Its just generating a new playerprefs when a product is purchased
If you have a shop in a game for buying avatars and someone buys something, you dont want them to buy it again
So I want to only instantiate playerprefs that they own (for the tab where they can equip their purchased ones)
you can use
PlayerPrefs.SetInt("item" + itemIndex , 1);
to store the purchased items
and
```PlayerPrefs.GetInt("item" + itemIndex) == 1````
to get if an item has been purchased or not
No, because when theres 50 items in the shop we dont want to check each individual pref
so dont use playerprefs
regardless of save method youll need a loop
you could also use the int as a flag, and store 32 bools per int
but like
just
dont use playerprefs
why not
because thats weak code, using else if that many times
what?
youd rather just use a foreach loop to check the array for all the items you do own and instantiate those into the shop
just use a loop
I know to use a loop, thats not the question I asked. I am asking someone who is smart enough to give a detailed code
Thats what I have so far
Which is likely wrong
that wont work
productArray.Count is always the same
you need to use a normal for loop
what are u trying to do ?
for (int i=0; i<productArray.Count; i++){
var product = productArray[i]
if (PlayerPrefs.GetInt("item" + i) == 1)
//whatever
}```
inspector has 50 product prefabs, the shop instantiates all of them that you have not purchased yet, the ones you have not purchased are playerprefs 0. How do you instantiate a prefab like that
^
so each item is either bought or not?
why not Dictionary
Code example?
I have one tab where ppl equip owned items, and one tab where ppl buy new items
so on start I generate the playerprefs to the size of the array. Now for next loading when it will instantiate all the products that are 0(not bought yet)
what is productArray?
oh
array of gameobejct
array doesnt have count
it has length
cause its fixed
I added the ], sorry. But thats the code so far
So it should instantiate all the purchased prefabs only
such as producttype9
hi,
i have a drag and drop situation , where i want to get the item the mouse pointer is hovering on once drag ends to make a drop
public void OnEndDrag(PointerEventData data)
{
GameObject go = data.pointerDrag;
if(go)Debug.Log($"go:{go}");
}
the value of go is always the original parent before drag , not sure why
i also did that
public void OnDrag(PointerEventData data)
{
Debug.Log($"Draging :{data.pointerDrag}");
}
also the original parent even though iam hovering over many other objects
is there is a way to just get the object underneath the pointer at anytime regardless of the drag event ? cause it seems to be buggy
Could be like a raycast problem perhaps? Is there something blocking what you're trying to drag? For detecting what's underneath the pointer when dragging, I would assume you could just cast a ray yourself assuming you've not repositioning what you're dragging (and is under the pointer blocking the ray)
thanks , i will try that 🙂
I would still use a dictionary
I havent really used it for a while, I just remember a lot of the drag events being fluff. You only needed like the OnEndDrag for it all to work. (still, the other events are needed to display you 'moving' the ui element for the user)
My debug log says its going to spawn 3 different types of prefabs, but it only spawns prefab #2 three times, whys that?
I would not use rely on playerprefs for this..
its already working tho. The instantiate code just seems wrong
just cause it's working doesn't mean it's not flimsy code but I guess
Im not staying with playerprefs, its just the fastest way for now so I dont need to write obsessive classes for file saves
well debug your PlayerPrefs.GetInt then
so you know the value ur actually getting
not everything needs to be 1 liners
var productIndex = PlayerPrefs.GetInt("producttype" + i); Debug.Log(productIndex )
Ah I see what went wrong. im getting the value of the prefs
The value is always going to come out as 1
is product type supposed to be a bool
When you buy something from the shop it takes the product ID and sets its int to 1 as you now own it.
Now I need to instantiate all of those that exist/purchased
So the player can equip it
I can solve it tho
Instead of setting each product to 1, set the product to the product id
what's wrong with
public class Product
{
public int Id;
public string Name;
public string Description;
public GameObject ProductGO;
public Product(int id, string name, string description, GameObject go)
{
this.Id = id;
this.Name = name;
this.Description = description;
this.ProductGO = go;
}
}```
then you on purchase store them in your player inv..
List<Product> for example or Dict
each of the products have unique details, so its not really modular. The purchases are going through server side rn
When building a mesh through code (i.e. creating a vertice array and a triagle array), how would I specify which colour should be used for each triangle?
Im fudging around with a save system, and Im wondering if there is a nicer way to give many instances of a prefab a unique key to save wether they have been collected or not? Right now im just randomly typing a string in
GUID
Elaborate?
You mean when you save with the items you collected you don't want to reload scene and find the stuff you picked up right ?
exactly
yes make each object have a unique Id with GUID
incorporate that On Loading /Saving
How would that differ from manually typing in a string?
yeah it's faster and more efficient
Ah sorry for confusion , my old script I still stored it as string
but with GUID
public string ID => _id;
private void Awake()
{
idDatabase ??= new SerializableDictionary<string, GameObject>();
if (idDatabase.ContainsKey(_id)) Generate();
else idDatabase.Add(_id, this.gameObject);
}
``` for example
yeah i got it working 😄
the only thing is, if there is a way to make this happen when i drop something into the scene, so i dont have to remember to go use it on every object
[ContextMenu("Generate ID")]
private void GenerateGuid()
{
id = System.Guid.NewGuid().ToString();
}
void OnValidate() ```maybe check if has ID already
if not generate
I store mine in a DB
so I check the Dict
ill try it, otherwise ill just make it crash the game if it hasnt got an ID so i cant miss any :p
yeah I have a serializable dictionary i put all the "flags" in, but I so far I only had big stuff, not large amounts of pickups
how do you get the text like that
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
how do I retrieve data from an sqlite database and output it into a text object?
do you have method to save /write ? you should be able to just use the Read method then put ito text
this is what i have so far, this class creates all the methods for my database, what i want to be able to do is call a method from another class to retrieve for example the first name of a student with a certain id number
here I do this ```cs
using(IDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
var instance = Instantiate(itemPrefab, rootDbItems);
instance.SetItemText($"{reader["name"]} {reader["damage"]}");
}
reader.Close();
}```
[SerializeField] private TextMeshProUGUI itemText;
public void SetItemText(string text)
{
itemText.SetText(text);
}
}```
map this data into an object
so you can retrieve it whenever
would i be able to put that method into my 'DatabaseMethods' script as its own method and call it from another script?
look my suggestion above
unless you update the data often
otherwise you could put it into a method ofc
on my example I map my object like so
public class Item
{
public string Name { get; set; }
public int Damage { get; set; }
}```
List<Item> items = new List<Item>();
```cs
while (reader.Read())
{
Item item = new Item();
item.Name = (string)reader["name"];
item.Damage = (int)reader["damage"];
items.Add(item);
}
reader.Close();```
v1.2.0 is here 🙂
https://github.com/kingdox/UniFlux
okay, thank you for your help, appreciate it
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Really should implement your own constructor with expected parameters value.
@potent sleet, i didn't fully understand your examples but after googling i came to this method to call information from the database, however this error keeps popping up from the first screenshot which when double clicked into sends mi the this specific line in my code in the second screenshot
I have a object with a script "Game Manager"
And i instatiate a object that on start gets that script from Game Manager:
floor_Teams_Data = gameManager.GetComponent<Floor_Teams_Data>(); ```
and another action uses some function of that floor_Teams_Data reference and i get an error that "Object reference not set to an instance of an object"
I look at the inspector and the reference is there
What steps can i do to debug this? I lost almost 30 min trying to find a solution
Is there a way to slow down time only inside a capsule collider? This is what I have atm
I use this to generate the shape but I don't know what to do next
What do you mean "to slow down time only inside a capsule collider"?
I think I understand what you want to achieve, but it requires handling your own physics setup. You'd need to handle all of your object velocity to be able to control "time" when inside a trigger volume.
ah ok
I used the script about to assign a gravity modifier only to that area and it works so far
and I was wondering if I could do the same.
^
hit.transform.gameObject.GetComponent<Rigidbody>().AddForce(new Vector3(0, -30, 0), ForceMode.Acceleration);
anything that hits that generated capsule gains a gravity modifer
could I just swap it and do
Time.timeScale = scale;
Time.fixedDeltaTime = scale *.02f;
?
something like this kinda?
try using statements
hit.transform.gameObject.GetComponent<Rigidbody>().Time.fixedDeltaTime = 0.02f *?
private void DisplayWeapons()
{
using (var connection = new SqliteConnection(dbName))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = $"SELECT * FROM {WeaponsDB};";
using(IDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
//etc..```
@zenith iron
mine right ? it's really old xD
The problem is that you're using a Unity game engine where physics is already built for you. What you're trying to accomplish goes beyond than using Unity's default physics. You would need to handle your own physics solver to achieve "slow" and "timed" movement.
My object has an instance each of Script A and Script B.
During Awake(), Script A references a UnityEvent in Script B, and adds a listener to it to run a function in Script A.
Awake() in script A runs properly, and so does the UnityEvent in Script B, but the listener is not running. I think it's not being added in the first place (possibly due to the event somehow being triggered before Awake() runs), but I don't know hot to check this.
All of UnityEvent's built-in functions only work for its persistent listeners, so I can't use those.
Thoughts?
Share the code.
no can do, I'm under NDA. I got an idea from another guy to run it in Start() though
public void ContarCantNoticias()
{
dbReference.Child("noticias").GetValueAsync().ContinueWith(task =>
{
if (task.IsFaulted)
{
Debug.Log("TASK FALUTED xD");
}
if (task.IsCompleted)
{
dbReference.Child("noticias").RunTransaction(mutableData =>
{
IDictionary<string, object> cantNoticias = (IDictionary<string, object>)mutableData.Value;
Debug.Log(cantNoticias.Count);
debug.text = cantNoticias.Count.ToString();
mutableData = null;
return TransactionResult.Success(mutableData);
});
}
});
}
When I add this 2 lines of code it works on the 2nd time I call the void (I dont want this to happend):
Debug.Log(cantNoticias.ToString());
Debug.Log(dbReference.Child("noticias"));
But if I remove them it just stops working (also dont want this to happend tho)
@cosmic rain okay putting it in Start() works
When building a mesh through code (i.e. creating a vertice array and a triagle array), how would I specify which colour should be used for each triangle?
You can set color per vertices, not triangles. For that there's Mesh.SetColors() method.
Might want to give some more details...
I just went to sleep, tmrw I will send it, sry
i've tried 'using' statements, but it still it giving me this error every single time no matter what i change for the line shown in the second screenshot
can i pay someone to teach me coding?
are you using the correct dll?
@potent sleet what version of unity are you using?
fuck
2021
erm, i assume so
was it working before
you got the right Mono from correct editor version ?
it should be in your Unity installed folder
yeah from the version i am currently using, i will delete it and try again just to be sure i put the correct one in
what version are you on , iirc is in the unityjit folder
then it might be the wrong one
you think the dll file in the 'unity' folder is the wrong one?
i'll give it a go
what do you mean?
did you not download the SQLite precompiled binaries ?
oh you mean download the x32 version of it?
nah x64 should be fine
oh yeah that's the one i originally downloaded
Has anyone run into this weird issue where I'm trying to write/compile a shader, this message pop up from a different file?
What does it means??
When unity compiles shaders it expands the macro's in other files. Are you using any unity macros in your shader?
I think that was it... I was using UnityCG.cginc
Nope...
@potent sleet not sure jif was the correct version, now giving me a different error
gonna attempt to run the code on my mac see if that does anything different
strange.. tbh haven't using SQLite in a year, I switch to nosql / document based DB
here's my dll
can you use nosql in unity?
I use Realm with MongoDB
there is also google's Firestore. or w/e is called
idk thats what they call it
https://firebase.google.com/docs/firestore
I never use it, I'm a mongodb fan so I stick to that
is it easy to use with unity?
might have to give it a go, this sqlite is fucking me off
it's much easier to work with a Object based db
depends on your usecase ofc
fuck writing sql code
lol yep, i only chose to use it because i'd done it before
def give Realm a try if you have no problem working with POCO
I still like writing SQL code tho...
PHP flashbacks
back at my old job, I wrote 200 lines of SQL code, it was primarily used to generate material resource planning.
Several temp table was created to hold information and output tons of planning. Which was kinda cool to learn.
idk what POCO is tbh
was it enjoyable tho 😆
Plain Old C# Object
Plain Old C Object 😄
I'm getting this error:
RenderTexture.Create failed: colorFormat & depthStencilFormat cannot both be none.
when I call this:
Camera.main.Render();
but the render texture is set to this:
RenderTexture rt = new(Screen.width, Screen.height, UnityEngine.Experimental.Rendering.GraphicsFormat.R32G32B32A32_SFloat, UnityEngine.Experimental.Rendering.GraphicsFormat.None);
or this (tried both):
rt = new(Screen.width, Screen.height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB);
But neither of those have both colorFormat & depthStencilFormat set to none, so I'm very confused. Any help with this?
You've got the color format as none.
where?
4th parameter
Here's the docs: https://docs.unity3d.com/ScriptReference/RenderTexture-ctor.html
even then, they both aren't none
The 4th was explicitly set to none by you.
UnityEngine.Experimental.Rendering.GraphicsFormat.None
like I said, I'm using the constructor where the 3rd parameter is the color format.
even gave a screenshot
Look at the docs...
There are only three overloads and only one taking more than one argument.
some are excluded because it's the same thing but without some 'optional' variables.
this screenshot is directly from the RenderTexture class
Well I'm not sure then.
I'll try using the one in the docs but
Error is never wrong so 🤷♂️
What's the stacktrace from
this is the full thing:
RenderTexture.Create failed: colorFormat & depthStencilFormat cannot both be none.
UnityEngine.Rendering.RenderPipelineManager:DoRenderLoop_Internal (UnityEngine.Rendering.RenderPipelineAsset,intptr,System.Collections.Generic.List`1<UnityEngine.Camera/RenderRequest>,Unity.Collections.LowLevel.Unsafe.AtomicSafetyHandle)
CharacterMovement:GenHitParticles (UnityEngine.Vector3,UnityEngine.Renderer) (at Assets/Scripts/CharacterMovement.cs:318)
CharacterMovement:HitCast (single) (at Assets/Scripts/CharacterMovement.cs:293)
CharacterMovement:Hit_performed (UnityEngine.InputSystem.InputAction/CallbackContext) (at Assets/Scripts/CharacterMovement.cs:278)
UnityEngine.InputSystem.LowLevel.NativeInputRuntime/<>c__DisplayClass7_0:<set_onUpdate>b__0 (UnityEngineInternal.Input.NativeInputUpdateType,UnityEngineInternal.Input.NativeInputEventBuffer*)
UnityEngineInternal.Input.NativeInputSystem:NotifyUpdate (UnityEngineInternal.Input.NativeInputUpdateType,intptr)
line 278:
private void Hit_performed(InputAction.CallbackContext context) => HitCast(hitForce);
```line 293:
```cs
GenHitParticles(hitInfo.point, hitInfo.collider.GetComponent<Renderer>());
```line 318:
```cs
Camera.main.Render();
would the render texture somehow be getting reset?
I have it stored in the class and never changed so I wouldn't think so.
Slightly scary where you're rendering the main camera from, but I won't question that part too much
You'll probably have to show where you initialise the RT
You should be calling Create yourself if you haven't already
(and Release for that matter)
yes it is scary. I couldn't figure out a way to get the pixel color from the screen in a different way.
would I really need to call Release if I just reuse the same render texture over and over?
You use it when you're done
anyway, why are you not using the Scene Color that render pipelines provide? https://docs.unity3d.com/Packages/com.unity.shadergraph@14.0/manual/Scene-Color-Node.html?q=Scene Color
because when googling "How to get the color of a pixel on the screen in unity" didn't come up with this
it only showed post after post about rendering the camera to a render texture
even better that this is shader graph. I'll look into using this, thanks.
But for the error... unity bug? I added rt.Release() after I'm done with it and still doesn't work, same error.
@potent sleet so SQLite works on my Mac, thought you might like to know. I must’ve been doing something wrong with the dll files, gonna have a play around to try and fix it
Hey everyone, this might be a beginner-ish problem, so I apologize to put the thread here, but I'm having an issue with the reload function for my gun. I really haven't the clue what the exact issue is so i'll just send the code https://gdl.space/tepivuzino.cs Please let me know if you need any more info, I'll gladly send it
what's supposed to happen and what is happening?
I only sent the part with the reloading because that's the issue. Can you tell me what exactly do you not understand so I can properly elaborate?
you said that you're having an issue with the code but didn't say what the issue was, could you start by saying what the issue is?
I know you said you don't know what the issue is, obviously if you did you wouldn't be asking here, but what's happening with it right now?
Ahh nvm I reread your question. In any case, nothing happens, the magazine I have stays at 0 once I empty it and the function never happens, and what is supposted to happen is, after the R key is pressed the reload starts, it lasts for "gunData.reloadTime" which I set to be 1,5 seconds and the current magazine should be equal to the overall mag size
hmm well first I don't think you need the ?. operator to invoke an Action, could be wrong though.
second, have you put debug log statements in the if statement that gets the reload input to make sure that works?
third, have you tried putting debug log statements in the reload function? Could gunData.reloading be set to true already? maybe it's not getting through that. As for the activeSelf, I'm just going to assume that's true, although you don't need this to access gameObject.
Next, have you put debug log statements in the Reload coroutine? In the code you sent you have a typo, gunData.reloadTIme, I assume it's supposed to be gunData.reloadTime. Also, could that value be very large?
Finally, could gunData.magSize be 0?
@sweet basin that's everything I could see that could be wrong, besides the fact you should probably unsubscribe from those events in OnDestroy() or something.
I sincerely apologize to say this but I don't understand what you mean with the second and third point. I'm quite new to game development and I wasn't too deep into programming before this either so it's really hard to understand. As for the ?. operator, I'm confident it's not an issue because the action before reloading, the one that deals the actual damage to the target, works just fine with the same operator. And as for the fourth point, yes I made a slight mistake with the reloadTime typo, managed to correct it but the issue is the same still.
using Debug.Log(object); at various points in the code to print to the console is what I mean, to verify it's reaching there.
Ohh yeah I also tried changing the values, so that's not the issue also
Ahh right, I can try and send the results. Hopefully I'll manage to set it up
@sweet basin first, can you send a screenshot of your IDE?
are you using visual studio? I want to check if it's a "miscellaneous file" or not.
Yes I'm using visual studio
top left does it look like this or say "miscellaneous file"?
ah ok, so it's not something easy we missed then, compiler would have complained.
yea, just try the Debug.Log statements. I would literally just do
Debug.Log(1);
Debug.Log(2);
Debug.Log(3);
....
and so on, and see where it doesn't reach.
For every function?
no
In the code that you sent (I don't know if these line numbers match up to your cs file) I'd put one after line 21, after line 47, after line 49, after line 55, and after line 57.
Uhh non of them pretty much
I have emptied the mag and I got no info after trying to reload
I tried to see if I did the debug wrong by putting one message on the shooting command also, but that one worked just fine and I got the info
And so I deleted it
so I suppose it's not detecting the reload key
you put a Debug.Log() statement inside of the if (Input.GetKeyDown(reloadKey)) if statement right?
you're serializing the field, are you sure it's set to R?
nonono, in the inspector
I mean I did type the KeyCode.R after it
when you Serialize the field it exposes it in the inspector, so it could be changed.
check the inspector of the object that has the PlayerShoot component
Sorry, I'm a bit confused... by inspector I meant the thing on the right side of unity, as shown in the screenshot you sent here
just click on the object that the PlayerShoot component is attached to
Yes, but it wasn't there, If I delete the [HideInInspector] I can see the bool element
yes, but that's not what I'm talking about. I'm talking about this
it seems that reloadKey is assigned something else in the inspector.
I'm so sorry to bother you like this and lack so much knowledge, but I really am not sure how to check that
I just went through every folder and script and I have nothing
With reload
Ohhhhhh nvm I realised what you were talking about, I forgot to add the PlayerShoot to my gun...
I was sure I added it since I added the Gun script also
I mean I was sure everything in the inspect was right, so I only focused on the code
I see it works now, thank you for all the help anyways, and I'm sorry to trouble you like this
lmao
so unity uses components. When you create a script by default it can be attached to any game object. I was trying to ask you to select the gameObject that you had added that script to and check the inspector, the panel on the right side of the screen.
Yes I know that, I understood later what exactly you meant, but I thought that I had already attached all the scripts
That's why I really didn't understand the problem
I am a bit confused
Vector2.SignedAngle gives me 0
when I pass: from -17,-8 ; to 0,0
am I doing something wrong?
I need to get Y look angle from one position to another
0,0 is not a direction
Any idea why this appears when I call DontDestroyOnLoad on referenced object but only after I start play mode more than one time? The first time I start play mode after rebooting Unity, I don't get errors, then I get this 3-5 times at start. Doesn't seem to stop the script though so no impact but still weird...
Hi guys! I have a question regarding coroutines. So assuming I have a code like this:
{
if(x)
{
print("hi");
x = false;
}
else
{
StartCoroutine(UpdateX());
}
}
private IEnumerator UpdateX()
{
yield return new WaitForSeconds(1f)
x = true;
}```
will the coroutine keep on starting again at the beginning before it could pass the if condition in the Update() function?
Depending on which Unity version you are using, you might want to update your TextMeshPro package
yes, for 1 second, which is a lot of Update cycles
put the x = true before the yield to stop this, but it will only half the problem
It wont keep starting at the beginning. It will constantly create a new Coroutine and the ones before that will also continue to run. Starting a coroutine twice does not mean the first one will be aborted
So in your case, it will be started as often as is possible in 1 scaled second
So assuming you run at a constant 60 fps, and your timescale is unchanged, 60 Coroutines will run at once
So this is probably not a good idea
Thanks for this but the way that I intend to use the code is so that there's a delay. Would you have any suggestions on a better way of doing delays?
I plan on just putting another bool
exactly
bool isRunning = false;
private void Update()
{
if(x)
{
print("hi");
x = false;
}
else if (!isRunning)
{
StartCoroutine(UpdateX());
isRunning = true;
}
}
private IEnumerator UpdateX()
{
yield return new WaitForSeconds(1f)
x = true;
isRunning = false;
}
yea exactly what im doing now lol
perfect
been stuck on a bug regarding input for about an hour
and I had to act like a controller for an hour to understand it
thanks for the help though!
@fathom plaza tbh you could just do
private void Update()
{
if(x)
{
print("hi");
x = false;
StartCoroutine(UpdateX());
}
}
private IEnumerator UpdateX()
{
yield return new WaitForSeconds(1f)
x = true;
}
Hello, I don't know if this topic should be in general or some other code based channel, I'm looking for any source that will help me to implement Fog of War, something like Warcraft 3 Fog of War, best practices etc 🍻
Thanks, I will ask there
any better way to implement this?
Nah I can't. My purpose for the code is to prevent inputs from overlapping. Since in 1 frame, there are 2 scripts that make use of controller inputs that trigger the same function, it tends to overlap. That's why what I did was in the latter script that should run, I placed the inputs for it on cooldown for a short period just to prevent it form overalpping
So basically, I want the coroutine to start first
Yes, you can use a format string to display the mass: text.SetText(rb.mass.ToString("F2")).
Adjust the number after the "F" to show more or less decimals
Hello, Why does agent.remaining distance always returns 0? Has anyone ever encountered such thing? There's no errors, no issues with the gameObject and the target, the agents are set correctly
if i have multiple colliders can i know which one was triggered?
Attach a script to the game objects that has a collider and use debug.log("Something " + gameObject.name) in a ontriggerenter method
well yes, but if i have one on right and one on the left can i know when the left one is triggered?
or should i make defferent objects per side
OnTriggerEnter, you can't
You can't use multiple colliders on the same game object
Probably, with each one having a script that relays which one collider to the same script
And you can use multiple colliders per object
i see 
Would they all fire?
If they have the exact same bounds, yes
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
Group the colliders by meaning on child objects
so if three colliders are all hitboxes, put them all on a child object
and add a component that reacts to collisions accordingly
Hey, anyone got any idea how I could make the highlighted tiles on movable spaces for the rook look better? I'm tryna figure something out but cant get something looking good as my artistic skills is non existent
Outline shader maybe
hm, that could be an option, no idea how to make one of them though so i'd have to do some research
Hey Guys! Welcome back to another CG Smoothie Video! In this video I'm bringing you guys a new Unity Game engine tutorial! This time, we're learning how to use the unity game engine to make 3d outlines around characters and objects in your game using the Unity Shader Graph! I think this is one of the BEST Outline tutorials out there! If you guys...
Try these if you'd like
i actually tried that one with the chess pieces but for some reason it didnt work that well, when i tried it on pieces it wasnt great
Transparent Red/Green ?
Arrow ?
Single Dot ?
Transparent Mesh ?
Single Case ?
Oh I see
thing is right now, it doesn't change the actual tiles as its one prefab, its a square just above, and i tried transparency but its hard to see on white tiles. A singular dot could be a good idea actually
this is what i mean. I tryed following his thing exactly but i just couldnt get it right
very low poly models will not play nice with an outline shader
at least, ones that work by pushing faces out along their normals
I'm not sure but I think it might be a problem with the UV
ah right i see
Yeah I only really know the absolute basics for shader graphs to be honest, never really dove into it much
What you COULD do is make a separate mesh for the outline
do you know much about Blender/3D modeling in general?
i mean its not really a problem, i dont really need an outline anymore for pieces. It was just an idea for the tile highlights
I've tried it, but im not exactly great at it
this is what i have for highlighting pieces now on mouse hover
which looks fine so im not bothered about changing that