#archived-code-general
1 messages ยท Page 454 of 1
That's even easier. Set the whole board to zero except the last k elements being -1 indicating they are mines. Fisher Yates shuffle the last k elements, that's it.
Zero allocation, only k random calls and swaps.
I feels like the mines are more spread than that, like I never encountered this many mines in a row
because usually there aren't that many mines in a 10x10 board
I was looking for the % of mines in a grid and found a number between 10% and 20%
also the amount of mines is usually fixed, not random
and right now you have 24%
really ? ๐ค
yeah
yeah because in my case I choose a number between 10 and 25
where can I get the official numbers please ?
it's a Tile[,] so that would involve moving stuff around, no?
shuffling first then setting the mines would probably be easier
there are no official numbers, minesweeper is just a concept at this point
google's easy difficulty has 10 mines on a 8x10 board
minesweeper.online's easy difficulty has 10 mines on a 10x10 board
I don't see how 2D array changes things. 2D array is just a funny flat 1D array without you needing to convert the index.
also the first field is never a mine, the mines are generated after the first click
my point being it's not an int[,]
I don't see how that's different
if you set the mines then shuffle, you'd have to also reposition the actual tiles
You put empty tiles all the way up, except the last k tiles being mine tiles, and do the exact same algorithm
shuffling first then setting the mines would let you avoid that, no?
you'd have to reposition the tiles in the game to match the array shuffling
Also I think there's some difficulty-base adjustments to density, basically preventing certain higher numbers from being generated on lower difficulties. There's probably a research paper somewhere on how Minesweeper generates its boards
Didn't know that
Reposition while shuffling then.
But you can still make a perfectly serviceable Minesweeper with just pure random placement
shuffling first then setting the mines would let you completely avoid that
Yeah I mean, if this whole conversation is about the easiest way, then who cares about 100 allocations.
im not talking about adding allocations though
If we are going down the optimization route, the way I described would involve zero allocation and only k randoms and swaps, regardless of n.
...with those swaps involving repositioning gameobjects
i'm only talking about removing that last part
I don't get it, if you can "shuffle pure data first then position the game objects correctly at once" then why couldn't you also do the same thing but with my algorithm? Well, I'm not invested enough in this conversation tbh, seems like you guys have something already.
the gameobjects already exist
i am referring to your algorithm - in fact, i suggested a very similar thing
Also I have another question, how to make my grid centered on the screen please ? I tried to change the pivot point of my tile to the center, top right and bottom left but my grid is never centered ๐ฌ
this is the change im referring to
for (int i = 0; i < k; i++) {
target = random(i, n);
- a[i] = -1;
swap(a[i], a[target]);
+ a[i] = -1;
- a[i].position = i;
- a[target].position = target;
}
How did you do the coloring ? ๐ฎ
instead of setting mines and then shuffling them into the board, you would shuffle the board and set the mines to first k Tile refs
diff formatting
search for diff here - https://highlightjs.org/examples
discord uses highlight.js for codeblock formatting
And do you have an answer for this please ? โ๏ธ
set anchors to stretch/center?
more of a question for #๐ฒโui-ux
basically just make anchors symmetric and left/right 0
Hey guys! i have a problem that i dont know how to solve. I have script that handles all my inputs
onFoot.UseItem.performed += ctx => { if (!playerUI.isInventoryOpen) useSelectedItem.UseItemInHand(); };
like this, when i press lmb it calls function from another script
{
ItemSO itemSO = inventoryManager.GetSelectedItem(false);//what item is selected
if(itemSO == null)
{
Debug.Log("No item selected to use.");
return;
}
ItemSO selectedItem = inventoryManager.GetSelectedItem(itemSO.isUsable);//this reduces item quantity on use
if (selectedItem is IItemUse usableItem)
{
usableItem.UseItem();
}
}```
and from scriptable object script it gets UseItem of that SO
```public void UseItem()
{
// Implement the logic for using the seed item here
Debug.Log("used");
} ```
ill try to be as clear as i can, i need to check in UseItem for canPlant bool from my plantingmanager script, so if i can plant than i will use the item, but i cant get a reference in my SO to plantingmanager, if i will do it in my UseItemInHand, then every object even if its not a seed will have a check on canPlant which i dont want because i will have items other than seeds. i propably could just use old unput system and in every item use script i would wait for lmb input, but i wanna do it with new input system. I hope i was clear enough and at least someone can understand what im saying.
Wouldn't PlantingManager just be a singleton?
i dont want to use singleton
ur right
The alternative is to pass in some kind of context to the game world in UseItem or injected into the SOs at some earlier point.
AnimatorController.layers[0].stateMachine.RemoveState(AnimatorController.layers[0].stateMachine.states[i])
this gives me the ChildAnimatorState and i need the AnimatorState. any tips?
https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Animations.ChildAnimatorState-state.html
is it not just the state?
seems like osmal told you the same thing in #๐ปโcode-beginner too
i dont know, but unity is crying about it so i need to find some way to convert it from one state to the other
Does view.IsMine work right with how im making these 3 scripts? Sorry if I make a dumb mistake I'm trying to get into networking haha! FirstPersonMovement.cs https://hastebin.com/share/itokeqahuf.csharp Jump.cs: https://hastebin.com/share/iceqafijiv.csharp Crouch.cs: https://hastebin.com/share/gagoloboce.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
take a closer look at what i linked you, or what osmal said.
sorry i should go to networking
yes either there or there is a photon server (or forum?) pinned in there#archived-networking
And make sure to describe what isn't working, wherever it is that you're go.
!code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
AnimatorController is for editor only. You probably want to look at RuntimeAnimatorController or Animator APIs instead
i figured it out with yalls help, just needed to add another state to the end of my animator state grabing line of code
I have an issue where my character uses root motion to do a dodge roll, but it doesnt seem to move the character controller.
(the animator and CC are both on the parent gameobject so thats not the issue).
A tool for sharing your source code with the world!
Just know that any code using AnimatorController will not compile when you build the game
you're presumably still doing your normal movement code through the roll, no?
You would want to disable that and the CC probably during the roll
Yes the roll code is in the same code as the movement.
And I already do disable the movement when rolling
if (isRolling) return;
How about disabling the CC when that happens too
But im using the CC to move the player in the dodge roll lol
CC.move()
I thought you were using root motion on the animator to do that
are you sure about that? because doesn't the root motion mean the animation controls the movement of the transform?
In this Unity game development tutorial we're going to look at how we can combine a Character Controller with Root Motion, to make the movement perfectly match the animation.
We'll start with an existing scene that has an animated character whose movement is controlled by a script.
We'll then convert this scene to use Root Motion to move the c...
skip to 7:10
apparently it causes glitchy movement
Have you tried actually debugging your OnAnimatorMove?
i.e. is Vector3 deltaPosition = animator.deltaPosition; this value as you expect?
Yes, I debugged the deltaPosition, and it returns 0,0,0
which means theres eomthing wrong with the deltaposition
right so it sounds like your animation simply doesn't actually move the root object
think so
But the mesh
Actually moves
uknow?
jeez
yeah your right its the animation itself
In the animation I was moving the "torso" bone (which moved the whole character so i thought it was the root)
ihi quick question how come i cant see my scene until i go into game mode game mode bottom right
not a code question. but it is because your scene camera is far away from the contents of your scene (excluding the canvas which it is focused on).
double click an object in the hierarchy to have the scene camera move to focus that object
ah ok it would be design then im assuming thought it was a bug in code
it would not be a design issue either. it's just a general misunderstanding of the editor. #๐ปโunity-talk is typically the place for questions like that.
ohhh ok ty
It's over here
yeah i just realized that lmao since this isnt the right channel should i ask how to fix my issue in unity talk?
if you are building a UI put your camera on 2D mode, it will make more sense
yeah ima do that ty for reminding me of that button
i just cant figure out thebest way to make it so my sprites and what shows on camera fit the giant canvas unity made and if thats worth it
Sprites shouldn't be on a canvas
The Canvas should be for UI elements only, and things that aren't expected to move much
That's the canvas
wait so then why do i get a giant canvas for the game anyway if sprites cant go inside that area
seems like it already works fine?
the canvas is in a separate space to world space, it renders directly to the camera, don't expect it to line up with world-space stuff while in scene view
For the UI
You make the game in world space
you put the UI on the canvas
yeah i just feel buggered that that canvas isnt overlapped over the worldspace for me to see where everything lines up
but alr ty for educating me on that principle lol
it wouldn't really make sense since it an overlay canvas doesn't move in worldspace
You probably shouldn't be trying to line up UI elements with world space objects
mm i honestly just wanted the text to go about under the characters but still be ui buttons so i dont need to put them as sprites
so i see that too
put your canvas into Screen Space - Camera mode and assign its render camera. You will still need to do something about alignment for anything other than your reference resolution
im using procedural animation, and i got it to work mostly ive but i have the one small issue, when im swinging i want it to look at the swing pole but clamped, i got that mostly but when i go over a certain point it just flips and does this weird thing.
or, to make it simpler. Can anyone help me on how to procedurally animate one axis, i have the target and the bone that needs to point all setup. i just need to figure it out
Can anyone test my movement code and give feedback on it? btw if you do the map has to be the layer "Ground"
what specific thing are you trying to get feedback on, very unlikely someone will download this to put in a project
also use links to share entire classes
the feel of the movement
you'd be better off making a WebGL build of your game and asking for feedback on the movement.
I want to render the main camera at a lower resolution using a RenderTexture, but I don't want to display it through a UI Canvas with a RawImage. I assume it's possible to draw the result directly on screen, since the PixelPerfectCamera component seems to do this without using any UI. How can I achieve the same effect manually?
Why do you want to avoid the RawImage exactly?
Nothing specific, I just want to know if it's possible.
you can use renderer feature with URP and create a fullscreen effect
Thx
Hello guy pls check this game out and give me a comment about what you think about it my system storage device got crashed after spending 1year of development on this game
https://youtu.be/YDmw78AwEBQ?si=dTedVRx4MCt63EN3
This is not the right place for this.
#1180170818983051344
Ohh sorry
Please don't crosspost, thanks. #๐ปโcode-beginner
Hi everyone
how can I scale the touch input delta with the screen res to have a independent touch drag sensitivity ?
closest i got is dividing touch delta input with screen res
Hey, is there a better way to handle out of bound indices for neighbors of my Tile in a Minesweeper game without using alot of if statements ? Like would it work with the ? operator for instance or something else ?
Just put the checks in a function so you only have to write them once
IsInBounds(coord)
I'm not sure I understand why a straight up multiplier wouldn't be sufficient.
But wanted to know first if there's a better way / smarter way
You'd have to show your existing code so there's something to compare with.
to multiply with the screen res ?
To just multiply by the touch delta
i dont see how this would work, higher res will mean higher speed
The res is already factored into the delta
touch delta is per pixels
the bigger the screen, the highest speed
Not really. Pixels don't really translate directly to speed. That's more about screen dpi
so afaik delta isnt independant to the res
so its maybe due to screen dpi
I have no code right now, but the approach I have currently in mind is the if statements but I also thought about the ? operator but didn't try yet, so that's why I'm asking if this would work or even if there's another solution than that ๐
I don't see how the ? Operator would be useful at all
It's literally 4 if statements
Or rather 4 conditions you combine with && or ||
In the time it took to ask the question you could have written it
It's just if:
x < 0
or
x > maxX
or
y < 0
or
y > maxY
No?
something like grid[i+1][j]?.DoSomething(), so it doesn't crash and skips DoSomething() if's null / outOfBound
if statements are the typical approach
no that doesn't work - it'd have to be the subscript itself being checked, which isn't a thing
But that's a different question entirely
null could work like that, outofbounds does not
mhhh
Why do people think basic language structures like if need to be optimized all the time
>= on the max, but yeah
Depends what max is but yeah
i knew someone doing braceless if expresions to "gain perf" lol
less tokens to parse (only compiletime perf)
saves project size too ๐
sadly for him it was for gaining runtime perf
-3 + indent bytes per if!
No it's just like, I'm always asking to make sure that my idea is the "latest / best approach" to do something and also that a solution doesn't already exist that could make me spare "writing code time"
or -4 + 2 * indent + indent width if you make it inline!
don't worry about it
if you see a straightforward way to do it, it's good enough
But we're talking about a max of 4 lines of code here.
Even breaking this down into an array and a for loop would be the same number of lines of code
how's that 4 lines of code when there's 8 neighbours around each tile / cell ? ๐ค
โจmath โจ
Well you didn't say if it included diagonals or not
Anyway sure another way is an array of directions and a loop
My bad but I specified it's a Minesweeper ๐ฌ
an array of direction ? What's that ?
Sorry it's late
for dx in -1 to 1
for dy in -1 to 1
newX = x + dx
newY = y + dy
if newX < 0 or newX >= maxX
or newY < 0 or newY >= maxY
or dx == 0 and dy == 0: continue
// use newX, newY
/* or */
neighbors = [
[-1, -1], [ 0, -1], [ 1, -1],
[-1, 0], [ 1, 0],
[-1, 1], [ 0, 1], [ 1, 1]
]
for dx, dy in neighbors
newX = x + dx
newY = y + dy
if newX < 0 or newX >= maxX
or newY < 0 or newY >= maxY
or dx == 0 and dy == 0: continue
// use newX, newY
I don't understand why you would need to check 8 things
It's only 4 checks
We're talking about a bounds check I thought
oh yeah makes sense, I thought about when a cell is in a corner but yeah checking 4 directions would be enough to handle all cases ๐
See ๐
People call me crazy for not going straight to the solution I have in mind, while doing this makes me and other people trying to help learn something new too ๐
you aren't actually using vector2ints though, are you lol
this is part of its own contained system that you aren't using, so now you have to sync them - seems like a lot of work to pawn off a single if check imo
nope, I had Vector2 but as my tiles are on grid I could use Vector2Int, so all good ๐
were you not using a 2d array?
Oh yeah my bad ๐ฌ
whats the macro to know if its a dev or release/shipping build ?
yeah so... you now have 2 systems in play that you have to keep in sync?
yeah so let's avoid that ๐
im confused, do you have both the Vector2 and the 2d array to keep track of the position of each tile?
I have the 2D array of Tile and each Tile element has inside it a property called Coords that's Vector2Int
in case I need to use
yeah ok i see what's going on, it's basically a reverse mapping isn't it
I have no clue ๐
you have a mapping of 2 ints to each Tile and each Tile also has its key, those 2 ints
the disconnect is in how those 2 ints are represented - separately for the 2d array, and as a struct Vector2Int within each tile
and also how the bounds are defined - by the length of each dimension for the 2d array, whereas with Vector2Ints the bounds would probably be represented with a RectInt as you say
could be a dict with try get and no need for bounds checks...
but yeah you have 2 systems in play but they aren't overlapping, they have separate responsibilities, so not really an issue
what's with that grid
is that.. not the same as tiles
also wtf why is minesSpawnChances a Vector2Int lmao
eh whatever if it works it works 
grid[] is data part of the grid, while tiles is the array containing the Objects themselves
like the visual part
doesn't seem like they really need to be separated
What kind of project structure do you guys use/like. I'm currently basing it on modules, but i noticed that each folder will have the same folders like scripts, prefabs, shaders etc. I could have the like Assets/Scripts, Shaders etc... but i feel like there will be more coupling this way. Thoughts?
If you're familiar with namespaces then follow a similar convention using them for your scripts, as for unity assets there's plenty of ways to go about it but most of the time it depends how you're constructing those objects from those assets
Like understanding the difference between a global material you would constantly use between objects, and more those specific to a prefab.
Organizing by type and organizing by feature are the two common ways. Personally I believe organizing by feature scales better.
Big problem with some of the Unity asset architecture if you do just want a single instance of it, but unfortunately you need it to live in some directory.
You typically end up with tight coupling in games anyway and loose coupling just tends to hide the dependency
Being able to embed materials or SOs would be a gamechanger
You typically want as little embedded in a scene as possible.
You can embed mesh data in scenes but this is highly discouraged
Yeah but I've some projects where I do have a directory per prefab because it has dependencies on 4 materials and a dozen SOs
would be able to cut it down and just have a directory of prefabs
You could store the materials on the SO
And all the SOs in one asset file
With AddObjectToAsset
Yeah in my mind organizing by feature seems logical in scaling. I wanted just second opinions if I'm missing something, because most of the project structure I see / gets pushed is by file type (?)
You can minimize though, what I'm wondering is which approach does it the best
This unstructured codebase has been far easier to maintain than any attempt at heavy structuring I've used;
https://github.com/Wolfos/Adventure-RPG
Almost all runtime code is in one assembly, and the only attempt at decoupling is this
YMMV but I've found that codebases that try too hard to be well organized and decoupled end up achieving the opposite 
It works till you get to a point where it does not.
Decoupling is usually made for maintainability in context of scaling application.
With multiple people working together on a considerably long timeframe.
Well ymmv but again, I've found that the opposite was achieved by trying to centralize the codebase around some decoupling system.
You can definitely go overboard whether that's code structure or file system structure, but that doesn't necessarily mean going free style is going to work out fine.
Additionally it matters a lot more in a team environment than solo. With no discipline and everyone doing their own things, it gets out of hand real fast.
You end up with everything having completely needless dependencies
I have seen codebase with multiple script at 10k+ lines where you had possibly 100+ intertwined concept.
By example, the inventory was baked directly in the player.
Yeah I think about it more on a per-system basis rather than taking the codebase as a whole
I mean, we can simply look at what you have and find multiple case where what you did falls apart.
Obviously, in your case it works.
This is what matters. As long as you are able to navigate situation where you need to refactor it might be fine. (In a solo context.)
In a team environment, for the player and inventory example, even if you know these two are hard coupled in the project and you would never need to decouple them (which is a very fragile prediction about the future), just merely separating them into two files already provides many benefits, eg less merge conflicts when multiple people are working on this part of the code base at the same time.
Well of course ๐
But you're never going to fully decouple the player and the inventory
Ideally, you would want to.
By example, you might want to use the same system for loot
Which I have
So, you did that. Which is beyond what you were suggesting
Yep. Thinking about dependencies on a system-by-system basis, instead of hard rules on the codebase as a whole.
This is usually what people means when doing healty seperation of concept.
No idea what you mean by "hard rules".
Or improvise and make your treasure chest immortal player objects you can interact with
Bethesda-ass solution
Once upon a time I worked on a game codebase where everything was structured according to the PureMVC framework, which is based around a messaging system.
Every call to another object went through a message instead of through a method call
Because everything needed to be registered, everything was dependent on this central system. Self-initialization was simply not a thing. Everything was highly reliant on call order. Debugging was hard because call stacks were super long.
In a video game concept, MVC usually fall short. However, in an application you might want to apply it religiously.
Works pretty well in web dev yeah
Even though the kids complain that it's outdated ๐
MVC can still be useful for UI if you have a lot of it!
I've tried it once. Wasn't a disaster but felt kinda pointless maybe
Might be better with UI Toolkit
On topic of the inventory/player relationship and MVC, ideally the inventory shouldnt know about the player and only invoke events upwards, but half the time I can't be bothered and just do bi-directional references
Similary with active elements like slots
Having the code decoupled is fine, sure. But having it decoupled completely via events is just overkill
You'll probably know from the start that inventory can't rely on player so that's not a good dependency to make.
But for the most part keeping it simple makes refactors easier.
I am trying to add a waypoint that indicates the location of an area of the map of my game using a canvas with screen space camera and dragging the main camera to the render camera and with an image as a child that contains the arrow sprite that will appear on the map but I don't know why nothing appears, the sprite appears as if it were outside the map, I don't know why it doesn't work, I have the objective assigned to it correctly too, with the transform.
My main camera is orthographic and contains a cinemachine brain with a virtual camera that follows the player
And now I Will send the code
using Cinemachine;
public class Waypoint : MonoBehaviour
{
public Transform objetivo;
public RectTransform arrowUI;
private Camera camara;
void Start()
{
// Obtener la cรกmara de Cinemachine
camara = FindObjectOfType<CinemachineBrain>().OutputCamera;
}
void Update()
{
if (objetivo != null && camara != null)
{
Vector3 screenPos = camara.WorldToScreenPoint(objetivo.position);
// Ocultar si el objetivo estรก detrรกs de la cรกmara
if (screenPos.z < 0)
{
arrowUI.gameObject.SetActive(false);
return;
}
arrowUI.position = screenPos;
arrowUI.gameObject.SetActive(true);
// Calcular direcciรณn y rotaciรณn
Vector3 direccion = screenPos - new Vector3(Screen.width / 2, Screen.height / 2, 0);
float angulo = Mathf.Atan2(direccion.y, direccion.x) * Mathf.Rad2Deg;
arrowUI.rotation = Quaternion.Euler(0, 0, angulo);
}
}
}
holy fuckerino whats this
For screeen space camera canvases you basically just use the world position of the object directly. It doesn't use screen space coordinates (confusingly enough)
i.e. pretty sure arrowUI.position = objectivo.position; would be more correct
would procedural animation be advanced or gen?
Just a bunch of Actions 
but, all i wanna do is get something to look at another but only on a certain axis, like a pivot
Does anyone have the Character Controller Pro and can tell me how it handles 90ยฐ ledges? My KCC slides down cause it thinks ir's a slope and I can't get it to work properly
very simple with Quaternion.LookRotation or just Transform.LookAt
still very simple
you're just skipping a step
you need to create a coplanar point first
then look at that coplanar point
how do i make a coplanar point?
for example, for rotating only on the y axis:
Vector3 lookAtPosition = whatever;
lookAtPosition.y = transform.position.y; // look at a point on the same x/z plane
transform.LookAt(lookAtPosition);```
This works well for world axes. If you need some arbitrary plane you can just use Vactor3.ProjectOnPlane to project your look direction vector on the plane then construct the rotation with Quaternion.LookRotation
but that wouldnt stop the x and y from also looking, correct?
I'm not sure what your question is asking
this will rotate the object on the y axis only to look at a point
is there any way that u can make an example of this in unity or sm, im not understanding this fully
this was my original post
Let's say you are the eyeball. You want to look at the black x mark. But it's above you, and you don't want to look up, only sideways
SO we take the position of the black x and give it the same y coordinate as the eyeball. That gives us the blue x mark.
Now you just LookAt the blue x
that's all my code example is doing
(the green and red are axis markers)
oh forgot to mention, this is a pivot, so it pivots to look at something
not sure I understand how this relates to the LookAt question
i want the pivot to look at the grapple bar
what is "the pivot"?
the watch claw
i see
so you actually do have an arbitrary plane you're dealing with
you can do this in one of two ways
but the actual code depends heavily on how the object hierarchy is laid out
thats what i want it to do
it has a root, and the actual bone for it is at 0,0,0
on the rotation
can you take a screenshot of exactly this but with the Move tool selected, and then another with the "Root" object selected and the Move tool selected?
so I can understand the orientation of the objects better
1 = the pivot
2 = root
they are literally in the same place and rotation lol
though the root has the script in it
can anyone help with this missing prefab error I'm experiencing on linux? I am new to Unity but when running on Windows the sim worked perfectly fine with the maps being loaded but on Linux there are errors.
ok so what you want here is to rotate on the root's right plane basically.
Something like this should work or get you close at least:
Vector3 direction = directionToGrapplepoint; // however you get this
Vector3 planeNormal = root.transform.right;
Vector3 projectedDirection = Vector3.Project(direciton, root.transform.right); // project it on the plane.
Vector3 upDirection = Vector3.Cross(projectedDirection, planeNormal); // I _think_ this will do it.
transform.rotation = Quaternion.LookRotation(projectedDirection, upDirection);
I'm making a system to create a simple hurtbox on attacks, and I have one issue. I want to be able to add as many "AttackModifier" scripts to the hurtbox as I want through the "CreateHitbox" method. The only issue is I don't know how to pass a script as a parameter and apply it to an object. What I have right now is this
void CreateHitbox([...] List<MonoBehaviour> ModifierScripts)
{
[...]
foreach (MonoBehaviour MB in ModifierScripts) { obj.AddComponent<MB>(); }
}
im not sure what the current issue you're experiencing is?
this code doesn't really make sense.
but also you can't exactly pass components around like this afaik
why are you generating hitboxes dynamically?
'MB' is a variable but it's used like a type
Yeah, it's the best I could try to come up with. I hope you at least see what I'm trying to do, that's mainly why I'm showing it
I want to spawn little damaging fields on certain attacks, to be clearer
Maybe this is what you want?
void CreateHitbox(GameObject theObj, List<MonoBehaviour> scripts) {
foreach (var script in scripts) {
theObj.AddComponent(script.GetType());
}
}```?
why not just make them statically and just enable or disable them dynamically
alr im back lets try it
I'll try that rq...
it kinda spazzes out
can you show your current code and a video of the spazzing?
Vector3 planeNormal = transform.right;
Vector3 projectedDir = Vector3.Project(target.transform.position, transform.right);
Vector3 upDir = Vector3.Cross(projectedDir, planeNormal);
Quaternion lookRot = Quaternion.LookRotation(projectedDir, upDir);
WatchBone.transform.rotation = Quaternion.Slerp(
WatchBone.localRotation,
lookRot,
1 - Mathf.Exp(-watchTrackingSpeed * Time.deltaTime));```
!code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Seems good so far, but... well I've already made an entire game but I haven't screwed this much with dynamically applying scripts so sorry if this is a stupid question, how would I even make that list in the first place? Because I have this....
public class ATTACKMODApplyBleed : MonoBehaviour{[...]}
new List<MonoBehaviour> { ATTACKMODApplyBleed }
ERROR: 'ATTACKMODApplyBleed' is a type, which is not valid in the given context
This is wrong:
Vector3.Project(target.transform.position, transform.right);
?
But how would I make a list of MonoBehaviors/scripts like I want to use?
you need the direciton vector, not the target position
Also you're using the wrong object
Vector3 planeNormal = transform.parent.right;
Vector3 direction = target.transform.position - transform.position;
Vector3 projectedDir = Vector3.Project(direction, transform.parent.right);```
i said the script was on the root
gotcha
Vector3 direction = target.transform.position - transform.position;
you still need to do this
Vector3 planeNormal = transform.right;
Vector3 direction = target.transform.position - transform.position;
Vector3 projectedDir = Vector3.Project(direction, transform.right);```
this is wrong too
WatchBone.transform.rotation = Quaternion.Slerp(
WatchBone.localRotation,
lookRot,
1 - Mathf.Exp(-watchTrackingSpeed * Time.deltaTime));```
For the moment change it to just:
WatchBone.transform.rotation = lookRot;```
we'll add the slerp back in later
can you show what it's doing?
hmmm that's odd... are there other scripts or anthing on the objects that are childre of the pivot?
At the very least the pivot should be pointing towards the point.
ye, just the actual bone, i made it a parent to make a pivot that faces the right way
no Ik
i just made the bone a child of a pivot cuz that way i can have the pivot at 0,0,0 but the bone is at 0,90,90
to face the right way
its not
Can you show the pivot object selected again? It really just looks like maybe I was mistaken about the orientations
Like can you show these screenshots but with the hierarchy in view too
yep the pivot
Because my code assumes WatchBone is the pivot
At this point I would start doing Debug.DrawRay with projectedDirection and upDirection
to make sure they're being calculated properly
nothing is popping up i dont see it
would it be drawline?
huhhhhh
its drawing it at the center of the scene
Praetor, im gonna add u on discord, ill be back in bout an hour then we can try get this to work?
Fixed by converting from SketchUp to .fbx
Hi, I want to use Graphics.RenderMeshIndirect to render a couple thousand meshes, I wonder if anyone could share some examples on how to use it to render meshes with texture and lighting
Unfortunately this is a little bit outdated as it's for DrawMeshIndirect but the concepts should be similar:
I'll check it out, thanks
unfortunately it doesn't tackle what I need, lighting and texturing, but I managed to use it to render a bunch of boids for a project I'm working on.
hi, i have a problem and cant solve it, maybe someone can help me.
player and enemy use both the same prefab like fireball for attacking each other. before the abilites launch, i give them a tag with it, that the ability knows who to collide with.
but when many enemies are attacking and i also atttack at ("kinda") the same time the tag get changed while flying or the projectile starts right away with the wrong tag and explodes instant on myself or the enemy hits hisself.
solution right now is, i have 2 prefabs, 1 fireball for the enemy and 1 for the player.
i wanna know if there are another ways to do it.
What is the difference between the two prefabs currently?
fireball? nothing
So why are there two different prefabs?
tried what
simple copied the ability
gave 1 the player and 1 the enemy
no more wrong collisions
Okay, and what are the differences between them
they are differently named xd idk ๐
Are you using the name for anything? Do you have any code that checks that?
So then what is the thing that you are checking to determine which one it is
seralizefield, so i set it up in the editor
No, what is the code doing that is determining which fireball is which
the fireball gets called from either player- or enemycontroller with a tag attached. so the fireball knows who to collide with
did i understand u right?
So do the two fireballs have different tags?
theres 1 string tag in an ability and i set them depending on which controller called it
So, that would be a difference
which you said there weren't any
If there's a tag that determines who cast it, you can set that after spawning the object from the prefab, then you don't need two prefabs
what is the difference that im doin right now?
I don't know, you haven't mentioned what you're doing right now until I wrestled it out of you over ten minutes
ah maybe i need to set the tag after it spawns instead of before
You can't set a tag before it spawns, it doesn't exist yet
you're changing the tag of the prefab
which would mean, the two prefabs have different tags
and are therefore not the same
why i cant set a tag before it spawns. its a seralizefield gameobject, so i can call methods there without spawning it, cant i?
The same reason I can't spend my trillion dollar fortune - it doesn't exist
Spawning creates the object. How are you going to set any data on that object before it exists
thats interesting and maybe the solution
Instantiate creates a clone of the prefab and puts it in the scene
The prefab object never actually exists
Any functions you're calling on it are changing the prefab
I'm building a 3D multiplayer mech game with a top-down perspective. Each mech is able to choose its loadout at the start of a match, and then it'll have those items equipped throughout the match. When I'm structuring my Robot Prefab, what principles should I be using to align with best practices? Specifically, I have a mesh for my Robot, but it needs to hold a gun - where should the object that represents the gun sit? Should it be a child of the Hand object inside of my Robot mesh? Or should it be a child of the "Robot" object? And then its visual is updated/rotated to match the location of the hand as it moves?
My understanding was that it's best to separate logical and visual elements, so my hunch was to create a PrimaryWeapon object as a child of "Robot". But I'm getting a little...brain-tied thinking about which objects should be responsible for which logic.
Something that might help is the Parent Constraint. It lets an object move as though it were a child of something, without actually being a child of it. That way you get the best of both worlds.
https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Animations.ParentConstraint.html
There is no particular way of doing it. The simplest is to use parenting. A bit more "organized" would be to copy the position/rotation of the object. You can easily do it with the Animation Rigging package.
You'd make the weapons be sibling objects that can easily be swapped out and not muck with the visuals, then you'd just need a script that knows which object the hand should be
Sibling objects of Robot, you mean?
Wait, sorry, sibling.
Interesting, so you propose that every weapon is a sibling of one another, with a common parent.
Anywhere, really. Wherever would be convenient
And then we toggle on/off which weapon is active?
ParentConstraint makes the actual parent hardly matter
What do you mean by that?
As I said, Parent Constraint makes the object move as if it were a child of something without actually being a child of it. So you could have the weapon anywhere in the hierarchy and just use a parent constraint set to the mech's hand
and you can set the offset and whatnot as well
Got it, interesting.
If there's somewhere you'd prefer to put it because you don't want it to be in the hierarchy of the visuals, you can put it wherever makes sense for your workflow without worry
Yeah I'd probably store it in the Robot object itself. Given that multiple players will be editing their robots on the screen at once.
And if a player drops out, that robot, weapons, etc. wouldn't exist.
Yep. And if there's a mechanic like looting weapons from destroyed bots, you could have the weapons be outside of that hierarchy so they'd still exist when the robot object is destroyed. It's a handy component
Got it. Interesting ok!
Most of what it does can be solved by juggling parent objects, but doing that makes it a lot easier to lose track of the object or accidentally destroy it. It's not really any new functionality, but great for organization purposes like this
So question about that then. I want to create a structure - I think - that allows the RobotController to activate "FirePrimaryWeapon(target)", and then the PrimaryWeapon fires a projectile. Naturally every weapon has different traits - damage, projectile speed, etc. My assumption is that every weapon should maintain knowledge of its projectile traits, and when spawning a projectile, it passes in the damage, speed, etc. (The projectile itself manages any unique movement)
So how would I build that programming structure to pass in the necessary damage to the PrimaryWeapon class? My first hunch was on Awake of any weapon, update the stats of its parent.
So I have a PrimaryWeapon class with a bunch of fields and a method called FirePrimaryWeapon(target) which is called by the RobotController when the player clicks the mouse, and a method called "UpdateWeaponStats". And then I have a Wep_Rifle class that sits on the actual Rifle prefab (a child of PrimaryWeapon) that, on Awake, calls UpdateWeaponStats(damage, speed, prefab, etc.) of its parent object.
But I have a hunch that...there's an easier, better way to accomplish this.
Ehhhh. Wait. That wouldn't be great because it would prevent me from creating unique firing traits - like burst fire or a flamethrower, etc.
one way is to use ScriptableObjects. You'd make an SO class that stores the weapon traits and assign a reference to it to the weapon script and/or to the projectile when it is fired.
e.g.
[CreateAssetMenu(...)]
public class WeaponInfoSO : ScriptableObject {
public float reloadSpeed;
public float shotsPerSecond;
public float projectileDamage;
// etc...
}```
I guess what I'm missing is: with Wep_Flamethrower a child of PrimaryWeapon, how do I activate Wep_Flamethrower's instance of "FireWeapon()"?
then your weapon script can be like:
public class Weapon : MonoBehaviouir {
public WeaponInfoSO weaponInfo;
void Shoot() {
float damage = weaponInfo.projectileDamage;
// etc.
}
}```
Does both weapon are available at the same time ?
There will only ever be one child of PrimaryWeapon active at one time.
Then you should instantiate only that one instead of having both at the same time.
So if the player equips Rifle, I'll first disable Flamethrower, and then enable Rifle.
Instantiate the Rifle. I believe you are going to have many, many more weapon
I will, yeah. And in a single match, the player will only be able to ever have a single weapon the entire game. Instantiation feels like it makes a bit more sense for that reason.
(They can't drop or pick up weapons)
(Even if they could)
Ok so my next question then is, how do I instantiate a weapon, ensure its position and rotation are set properly, and make its methods available to my RobotController class?
!learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
You should follower a course.
You are going to learn a lot which you are not seeing because you do not even know it exists.
Then things are going to make sense.
Sorry, that was a poorly-worded question. I know how to instantiate a weapon - I'm going to do so inside of the PrimaryWeapon class and track it from that class. And make calls down to the weapon's Shoot() method that it overrides from inheretance.
Thanks for the guidance!
I have a completely unrelated question: When I first started developing in Unity, my scripts would stay as active tabs inside VisualStudio 2022 even between compiling. But it seems now that sometimes when I compile my game, or when I add a new script, VisualStudio completely clears out my open files, which is getting REALLY annoying. Even if I pin them, they close my open files.
Does anyone have a hunch why that's happening?
You can try to regenerate the solution from the Preference Tabs -> External Tool
Alternatively, you could delete the library folder (it can takes a while) and reopen the project.
Thanks, I'll try these.
Otherwise, keeping it updated or reinstalling might works as well.
a lot of people have reported this recently. it might be an regression? (it's known where the issue comes from, i just don't remember it)
idk i don't use vs
Ok, good to know it's not just me. And it seemingly happened randomly so that's always fun. ๐
Hi, I'm working on a VR game so I have a player object that has the camera and both controllers as a child. But if the player moves in real life they will no longer be in the center of the player object which can be a pain when I want to move the player to a specific spot. So I'm looking for a way to always set the players transform at their head for example.
@steady moat @leaden ice Thanks for the help today, you both got me on the right track. I created:
- A PrimaryWeapon script that manages the PrimaryWeapon, instantiates it on a HoldPoint object on the mech's hand, and then call the equipped weapon's Shoot() method
- A Weapon class that defines a Shoot method, inherited by each weapon so I can GetComponent<Weapon>.Shoot() regardless of the weapon equipped.
- A WeaponStatsSO that defines fields that weapons will use to define damage, projectile speed, recoil, reload times, etc.
- A Wep_Rifle script that defines the unique shooting functionality of the rifle, overriding the Weapon.Shoot() class
And then I refactored my original primary weapon shooting code, ripped it out of the RobotController and put it in the Wep_Rifle script. Now the RobotController calls PrimaryWeapon.FirePrimaryWeapon() which calls Weapon.Shoot() and can shoot any weapon I attach to the PrimaryWeapon class.
The element I'm not quite sure about is the WeaponStatsSO. I'm calling it the way you mentioned Praetor, but I don't know if I'm using SOs to their fullest. It doesn't feel like they're providing me much more than what I'd write inside the class itself.
public class Wep_Rifle : Weapon
{
private WeaponStatsSO weaponStats;
[SerializeField] private GameObject projectileSpawnPoint;
[SerializeField] private GameObject projectilePrefab;
private void Awake() {
weaponStats = ScriptableObject.CreateInstance<WeaponStatsSO>();
}
private void Start() {
//weaponHoldLocation = GameObject.Find("RifleHoldLocation");
weaponStats.projectilePrefab = projectilePrefab;
weaponStats.damage = 10f;
weaponStats.projectileSpeed = 50f;
weaponStats.projectileKnockbackForce = 10f;
weaponStats.projectileLifetime = 5f;
weaponStats.lifetimeTimer = 0f;
}
public override void Shoot(GameObject _target) {
// Move all of this logic to the weapon itself
Debug.Log("Wep_Rifle Shoot(" + _target + ") triggered");
// Calculate the move direction to aim at the currentTarget, or forward if no target is set
Vector3 moveDir = _target != null ? (_target.transform.position - projectileSpawnPoint.transform.position).normalized : transform.forward.normalized; // FUTUREMAX This is going to need to be updated, because if there's no target, it will shoot out of the front of the gun - possibly at the ground.
GameObject projectile = Instantiate(weaponStats.projectilePrefab, projectileSpawnPoint.transform.position, Quaternion.identity);
projectile.GetComponent<DebugProjectile>().Initialize(projectileSpawnPoint.transform.position, moveDir, gameObject, _target);
}
}```
The way you are doing it here you don't gain any benefit from using a ScriptableObject.
The point of using a ScriptableObject is that you can create and edit them in the Unity Editor and reference them in the inspector
You wouldn't need to create more than one Weapon class
unless you had behavior you couldn't capture simply from the data.
I definitely do.
A flamethrower is going to be fired very differently from a rifle.
Though...yeah, I get what you're saying - it's possible the fire logic takes into account elements like "fuel", where a rifle might have infinite fuel. Then some logic that determines if fuel then fire.
regardless you definitely would need fewer classes. You don't need a different class for a rifle vs a pistol
Right. I understand. So an SO is like a container that makes fields available in the Unity Inspector - and these fields are individually editable on every object with a script that instantiates that SO?
on every object with a script that instantiates that SO
No, the SOs are assets in their own right
the MonoBehaviour script has nothing to do with it
SOs are just custom asset types
So from a practical perspective, do I place the SO on an object in the editor as an asset? Or do I add it as an asset inside of the Weapon script?
The part you might be missing here is the [CreateAssetMenu] attribute that makes creating them convenient.
Check the examples here: https://docs.unity3d.com/6000.0/Documentation/Manual/class-ScriptableObject.html
it's an asset
it lives in the project folder
like all other assets
Sorry, I confused the terms Asset and Component.
the Weapon script simply references it
Components are the things you attach to GameObjects
I know it's an asset. But it's not a component.
Right. Got it, yeah that I understand fully.
I think we might be on the same page, but using different terminology. My understanding until now was that the only way fields appeared in the inspector is if you used [SerializeField], or used [CreateAssetMenu] explicitly inside of a script. But in your Weapon.cs example above, you instantiate WeaponStatsSO weaponStats (using my naming here). And you're saying that the fields defined in weaponStatsSO would be editable in the inspector?
YOu are now confusing the SO itself and the field on your MonoBehaviour that refers to the SO
Refer back to my examples above. Here's the SO code: #archived-code-general message
And here's a MonoBehaviour that refers to an instance of the SO: #archived-code-general message
TO do this you:
- Create an instance of the SO in the project window through the Create menu
- Set whatever data on it you want
- Add the Weapon script to a GameObject somewhere
- drag and drop the SO from the project window into the field on the Weapon script to set up the reference.
Goooooot it.
There are more in-depth code examples here, along with how to properly use the CreateAssetMenu attribute: https://docs.unity3d.com/6000.0/Documentation/Manual/class-ScriptableObject.html
The SO script is defining what fields an SO has. And an instance of an SO actually defines the values for those fields.
yep
Got it got it got it. Ok.
same as a MonoBehaviour really except instead of being attached to a GameObject it just lives as a standalone object in your assets folder
My brain is expanding.
It takes some time to get back into the swing of OOP. That a single instance of a script (weapon.cs) can exist on multiple objects, each instance containing its own instance of the weaponStatsSO that defines the values of fields relevant to that weapon.
Sure - I think it's better to think of the weapon having a reference to a WeaponStats, rather than containing it
Absolutely.
But yeah classes in OOP are always like "blueprints". YOu can and often do build many houses from that same set of blueprints
is it really not possible to calculate a path using a certain set of weights for navmesh cells?
the only way to weight the pathfinding algorithm seems to be to give it GLOBAL area weights which rebake the navmesh
and apply to all agents
Did you try the navmeshmodifier
I understand that's a global modifier
that sets "area" which is like a terrain type enum
not setting the cost for a specific run of A*
plus it's done as a volume, is it not?
I want to tag each cell used in the path of an enemy, and trying to do that with a bunch of cube volumes sounds horrible
I suppose so , what do you mean for a specific run
Working with a mesh you are pretty much at the mercy of whatever unity coded in
im trying to make flanking behavior and it seems nearly impossible
so say one enemy walks right at the player through the most obvious doorway
I want to add all those cells to an "extra cost" array but only AFTER its generated the full path obviously
then I want the next enemy to account for that as like a weight mask, which would suggest it to take a different door unless thats the only door
but it also can't account for its own path, it has to apply once it has its path
and I might want other enemy types to not care what this one is doing
if one soldier guy goes through a door, a dog type chasing enemy shouldn't necessarily decide it needs to flank
but if I have to use a global area weight, it will
plus these areas are defined by like, volumes it seems
that float on top of the navmesh and carve it kinda
I want the actual navmesh triangles/polygons to be the shapes, not try to place a bunch of cubes all over the map editing the baked navmesh and then removing them and all that junk
basically I just want to take an agent, and say "run A* to find the fastest path, but add a weight to any node that the same enemy class took recently"
Found this BTW https://docs.unity3d.com/6000.1/Documentation/ScriptReference/AI.NavMeshAgent.SetAreaCost.html might be handy
I think combining this, with a bit of tricks with surface/modifier you can get around some limitations of built in nav
I saw that method but all that does is set the cost of a specific terrain type
which I don't really need
I think this is the same problem/same method I suggested before. #๐ปโcode-beginner message
Still not sure if what they want is possible with existing navmesh but truthfully doesnt seem to be
I need to dynamically set certain costs an a CELL BY CELL basis
That's all done in the backend by unity , you'd have to make your own system
what is o2n
typo sorry shit mobile keyboard lol I meant own
ah
Maybe the a* pathfinding project but doubt the free version would have such a gesture
well yeah, I think I DO need to somehow get a graph from the NavMesh and then run a custom A* on that and then do some other stuff to smooth the path
unity navmesh is like "baking...OK here is a mesh" hence the name lol
or maybe I can like, place a volume over each "doorway" that turns on or off, which carves the mesh but only in a smaller area
but then can I make certain "areas" only apply cost to certain units?
Also navmesh links are a thing too they offer some level of control over connecting areas
you can set a "walkable mask" but thats binary
can you make links have agent specific weights?
or agent-class specific at least
if you have 2 of the same agents though, i dont think this applies to what you want
I think it might work bawsi
might have to switch some types at runtime based on current needs
the problem I have with terrains is that they are the same for every agent
like "water" area is 50 cost or something
it's 50 cost no matter what agent you are
you can disable an area for an agent in a binary way but that's not what I want
but if links can say, "add cost for soldier agent type but not dog agent type" or something like that
then that MIGHT work, though it would require me to determine what exactly is a link and what isn't etc
same with modifiers it can apply specific costs to certain agent type
and it probably wouldn't just be something I can easily bake
those are a volume, right?
I think so yeah
can you have a static volume that doesn't change the navmesh triangulation constantly
But also you shouldn't be baking an entire level, I use multiple navmesh surfaces depending on use case
a link is to connect 2 areas of your navmesh, if all you're doing here is adding a link then it's going to calculate that it can just move directly across a link. i dont see how this solves anything really.
the placing a volume over each doorway i believe is something i suggested once, and really I think doing that would be the easiest way if you want to stick with navmesh
Links is useful for creating a connections between two points on navmesh without rebaking
so it IS possible to have a static volume over a doorway that cuts up the mesh once at baketime and then just changes the area of a subset of the triangles for SPECIFIC agent types?
area is such a confusing word for this use case, terrain type whatever
i think the way you described this last time was that you wanted this feature per agent. Not per "agent type" which would be your "Humanoid" etc
I was envisioning it in the context of custom A* where I would be applying a kind of "mask" of tris to the cost function each time but I think agent type would work just fine honestly
enemy type A would coordinate/flank, but would not coordinate with enemy type B etc
which I think is totally workable, if I want a bunch of enemies to surround the player I just need to make sure they are the same agent type
and that wont affect the pathfinding of an enemy that is more agressive or whatever
the only other question is, how do I determine all the volumes that need to be triggered when an enemy pathfinds?
like if an enemy gets a path that goes through a door, but it hasn't gone through it yet, how do I then tag that door volume?
can you test if a ray intersects one of those volumes?
this is why I thought custom A* would be cleaner, you just directly mark the nodes
gotta look better when I'm back but at least with links for example you can get the agent on it , probably same with areas / surface
plus I dont have to manually place volumes
on it currently, but what about for an entire path?
I dont want 5 enemies to approach the same door and THEN split up as soon as one touches it
The agent has info of its path
and I could convert the path into a sequence of rays potentially
ok I am kinda seeing the issue with per agent TYPE
a raycast wouldnt hit it, its not a collider. you also wouldnt have it active in the first place, this is something you'd need to manually figure out. if a volume is covering the path that you were walking on. The agent does store the path that it wants to take.
I do find it even more confusing what you actually want now. Maybe play around with navmeshmodifiers and volumes in your scene to see how it works because I feel like you think it's going to do something that it won't.
what I want is a pathfinding algo where each agent marks nodes that it's using, and OTHER agents avoid those nodes if possible
but since it seems that I cannot directly access the pathfinding OR the nodes in Unity...
volumes is kind of potential hacky workaround
the potential issue with agent TYPE though is that it can't ignore weights it set itself...
like say agent paths to green X, which then would trigger this doorway volume. but then it hears the player fire a gun and updates its path, however since it already marked that doorway, it's avoiding its past self even though it should "own" that path
that's probably why I wanted agent specific weights
not just agent type specific
maybe it can then pathfind to the new location both from its current destination and its current location and append to its path if the new location is closer to its destination? idk how cost intensive that is
with custom A* I could have a list of agents, and each agent has a set of nodes, and then when pathfinding it creates a weight mask of all agent nodes EXCEPT its own
and I would be willing to attempt custom A* if I could figure out how to get a graph from the navmesh triangulation unity gives me...
that's difficult to do since it's closed source / probably the c++ side
doing hacky shit is sadly the reality of working with a closed feature with its limitations
how easy is it to create your own navmesh?
the grid itself is pretty easy since there are so many articles/tutorials/example
I only personally did it with 2D though so I cannot comment on how to deal with elevations / slopes
I mean, I think it would be possible to create a graph of triangle midpoints based on the triangulation
I wonder how much you can extend on the free version of the Aaron berg A* pathfinding project
That had nodes options https://arongranberg.com/astar/documentation/stable/usingnodes.html
Introduction to how to use nodes.
it's just like, the actual smoothing of it, wrapping around corners etc
I can find the midpoint of each triangle and make that a coordinate node
and then if a triangle shares two verticies with any other triangle, make an edge
but that graph is going to look very jagged
A* itself I'm sure will be easy enough, I just need to apply an extra cost to a list of nodes every time it's run
the hard part is making that path actually look sane
like, I understand graphs and pathfinding on a graph. but I don't understand making that path fit nicely in a big polygon
maybe it doesn't need to look sane though? lol
if the player has line of sight to an enemy its gonna change its behavior anyways
so as long as it's not TOO innaccurate to the actual geometry of the place...
You might be overthinking it tbh
I dont think so unfortunately
if I can't have agent-specific weights then an agent can be blocked by its own pathfinding
I think with the function bawsi and I linked you(set agent cost) can be used to solve partial part of this problem if you still plan on using navmesh
set area cost or set agent cost
because set area cost has the same global problem and I dont see set agent cost
I can't figure out how to reference the NavMesh in code
its global per scene right?
I think it was , iirc you can now access the specific ones based on navmesh surface
I think I found it im checking rn
I'm on mobile rn its a bit of a pain to double check but yeah you can probably find that
I think I got it
now I need to make the code to create a graph from this, which I think is at least simple conceptually...
im back, if ur free u think u can help me fix this
If I understand the structure of the triangulation correctly I believe I have printed every triangle in the navmesh
I want to draw them in the game or something if possible, but idk if drawing 2K spheres will crash the game I guess we will see
no, you have made triangle soup
you need to use the index to determine which vertex to use
but not using the indices to look up the vertices, just using the ith index for the ith vertex
yes
ah ok thank you for catching that lol
whats the best method to draw like a sphere or something? DrawGizmos can do it but it applies to the scene view, when this information has not yet been generated
I just wanna see if I can calculate midpoints and see if they line up to the navmesh
draw a sphere out of what? the midpoints of every tri? DrawGizmos would work fine, just cache the points it should draw
alright i figured it out, kinda this code works when its the object is not a child of an object but not when it is a child, why is this?
transform.LookAt(new Vector3(target.position.x, transform.localPosition.y, target.position.z));```
btw this is code to look at an object on ONLY the y Axis
it's expecting a world pos and you're providing a weird hybrid point that uses world target x and z but local y which is an offset from the looking transform's parent
well that localposition i changed after i still didnt work after just inputted the normal .position, doesnt wanna work anyway
i tested, when the object that is doing the looking is NOT a child. It works fine, but when it is it just doesnt
it still looks at the object but doesnt do it one just one axis. it does it on all
if the looker is not a child, then transform.localPosition == transform.position
so you did something wrong if you "just inputted the normal .position"
it works either way
even if i just put in localpos it still works when not a child
refer to this
if looker has no parent, then
transform.LookAt(new Vector3(target.position.x, transform.localPosition.y, target.position.z));
is equivalent to
transform.LookAt(new Vector3(target.position.x, transform.position.y, target.position.z));
what are you trying to do exactly? You keep saying one axis but your code will potentially manipulate all 3 axis
you only want to rotate around y axis?
when its not a child it only does the Y axis
okay, got it to work, but now it only updates when im moving the camera
var relativePos = transform.InverseTransformDirection(target.position);
relativePos.x = 0;
var targetPos = transform.TransformPoint(relativePos);
transform.LookAt(targetPos, transform.up);```
btw rotating on the Y was just for testing
guys i need help, it's been 4-5 months since i started learning unity and i feel like that i'm stuck in tutorial hell already, i've been taking GameDev.tv course since 4 months and i've been really making a progress,
however i don't see it that it fits my overall perspective as i want to build a TCG/CCG and I couldn't even find any useful course that would teach me the logic of building such a game (like deck building / in-game stores / PvP / Drawing cards / holding cards in hands / etc)
I tried different courses and resources yet none of them is really that helpful which made me feel like I'm stuck in tutorial hell
any advice?
The point of tutorials is really to learn the basics and the building blocks of Unity.
When you go to make your own game you will use that knowledge and build things yourself.
It's not the case generally that you find a tutorial for building the exact kind of game you want to build
well you're totally right with that one, but i couldn't figure out the right programming logic for building a TCG/CCG like deck-building system, drawing cards, in game-store etc it's that what's preventing me from starting to make out my own game
you're mentioning three different systems there
the best advice I can give is that you need to focus on each thing one at a time
don't try to do it all at once.
they all are part of TCG = Trading Card Game / CCG = Collectible Card Game, they all are about these type of mechanics, drawing cards, building decks, buying cards, holding cards in hands etc (this is the type of logic that i'm struggling with)
I'm aware they are part of that kind of game
my advice remains the same
you must tackle each system one at a time
I see
well could you provide me a guidance? like a certain course or anything really?
even someone that has succeeded making his own TCG before
The biggest way to escape programming hell is being able to take a specific goal (eg. drawing cards) and deconstructing it down into the actual features required to make that work
-Held cards need to be stored somewhere (on a/the player?)
-Deck needs to be stored somewhere (on a/the player)
-Max held amount needs to exist
-Selecting a given amount of random cards from a deck
etc. etc.
then thinking about each of these features and determining what you don't know about programming that you need to know in order to achieve them
-How do i randomly select from a list
-How do i make other scripts reference eachother
etc. etc.
At that point you can start actually googling those things to get specific advice and learn
For what in particular? Again it sounds like you're looking for a guide to handhold you through the whole process of making an entire TCG game and it just doesn't work that way.
Besides if the game you're making can be boiled down to a tutorial that 50,000 other people have followed, well the game you make from that isn't going to be very unique or interesting then, is it?
So i just look at it like a problem solve the same way how we should be solving problems in programming (breaking down the entire problem into smaller manageable pieces?)
yes
that's just how problem solving in general works, yes.
you don't learn how to make games, you learn how to do the things that are neccasary to make games
Thank you so much i didn't know that i should be looking at it like this, it's why i was stuck
in other words i learn as i build my actual game ig
And because your learning these individual things, you compound knowledge that is super transferable for other future games
one last thing to ask you about, which game phase should i start with? the gameplay, main menu, deck-building etc? or should i just pick up one randomly and go on with it till i finish it and pass to the next phase?
go with whatever you think is the most interesting to start with
Start by having a shuffled deck of placeholder cards and being able to draw cards into your hand . Then you can build out your specific card rules around that
Thanks guys!!! I really appreciate your help!!!
totally start with designing cards with simple mechanics as that's the fun part
not so fun part is getting a nice arc and lerping motion when choosing said cards in hand
I already have that one in mind, like i settled down the game concept, the logic, the mechanics, the main idea of the game, literally everything (even the creatures design i have couples of them in mind) the only thing is to start actually developing the game, and i agree i already had so much fun during this phase (like settling down the game logic and mechanics)
The great thing and making a tcg video game is that you can actually make a physical prototype and playtest that
Before committing a single line of code
Thats what I would do
Your idea looks genuinely interesting, may you explain it more if you don't mind?
You sit down, design your mechanics and cards, then write them out on pieces of thick paper cut out the cards and start playing with friends
You then realise whats fun whats boring whats completely broken. You re-work re-balance
ngl that sounds pretty interesting and would help me develop a better mechanics for the game
and all while playing it
Iterate until you actually have a really fun card game and then itโs just a matter of coding it up
ngl your idea is genuinely interesting and pretty smart actually, it'll totally help me figuring out what game mechanics are more fun than the others before wasting time coding them
Thank you i appreaciate your help!
Just make sure to playtest with actual people. Go to your local shop and listen to the feedback. Games should not be made in a vacuum
yeah i totally agree with that, after all a TCG isn't gonna be a single player game it's game that you play with other people and having an immediate feedback on every mechanic i think of would be really helpful and would save me plenty of time
Exactly. No point on working on flashy card animations and foil shaders if your underlying card mechanics are shit
And your first iteration is going to be shit
I mean no offence thats just how game design works
none taken really i did work on a couple of projects while learning unity and i totally understand that lol
one last thing i want to ask, my plan is to make the game fully online, so while building the game should i be building it as an offline game then adds the online feature to it, or simply builds it fully online from scratch? i'm still an amateur in unity and getting a feedback on this would be hlepful
Build it with online from the start
Much easier to add offline play to a online game than adding online to a offline game
Hello what's up ?
I try to make a card game like.
I try to follow this tutorial : https://www.youtube.com/watch?v=bsPUDjijjTo but using the Balatro system made by Mix and Jam (https://www.youtube.com/watch?v=I1dAZuWurw4) as the base.
I don't know how to apply datas on the card instantiated. The Balatro system already instantiate the cards on the board. On top of that, for each card created, I want to call the Setup method that replace the datas(visual, titles, etc) on the visual of the card.
On the course I follow it has this structure :
Slay_Card get the datas from a scriptable object with all the info (title, images...)
Slay_CardVisual apply the datas on the card.
Now I have 2 other scripts that are supposed to connect all the datas.
I've got this script, it need to get the actual card create but I don't know how :
public class Slay_CardViewCreator : Singleton<Slay_CardViewCreator>
{
[SerializeField] Slay_Card_Visual card_obj;
public Slay_Card_Visual Create_Card(Slay_Card card){
Slay_Card_Visual card_visual = something to put here; <--
card_visual.Setup(card);
return card_visual;
}
}
and this test script, it get the scriptable object and call the Create_card method:
public class Slay_test : MonoBehaviour
{
[SerializeField] private Slay_CardData card_Data;
private void Update(){
Slay_Card card = new(card_Data);
Slay_Card_Visual cardVisual = Slay_CardViewCreator.Instance.Create_Card(card);
}
}
I try with Code copilot, chatgpt and every AI I found but that never work for me
Thank you
A Slay The Spire Unity Tutorial Series where we will build the game from scratch. In this episode we create the card architecture.
Support me and my channel: http://www.youtube.com/channel/UCtnH5bc2B74WhbdBpnpc9sQ?sub_confirmation=1
All those hours playing Balatro were purely research! I swear!
Support Mix and Jam on Patreon!
https://www.patreon.com/mixandjam
PROJECT REPOSITORY
https://github.com/mixandjam/balatro-feel
REFERENCES
DOTween plugin
https://dotween.demigiant.com/
MUSIC
--------------------...
I think I found the solution (with Code Copilot)
is there a c# definition to know what type of build is running ?
like UNITY_DEVELOPMENT, UNITY_SHIPPING, UNITY_RELEASE
i dont see any of thse or similar in the scriptign symbol reference, this surprises me
You can define your own https://docs.unity3d.com/6000.0/Documentation/Manual/custom-scripting-symbols.html
why such basic macros dont already exist ?
How should Unity know what development/shipping/release mean?
other engine does, i assume it can read what params are passed when compiling domain
I mean, what's to say my game must follow a software cycle like that, or what if I want a different cycle like development/staging/prerelease/release?
The point is that you can define whatever symbols and set whichever one to active yourself, via plenty of options listed in that page, automatically or manually.
im fine by adding it myself, but its very common to have stuff enabled/disabled depending on build type so i was surprised it wasnt implemented in engine core
Unity has build profiles, each profile can overwrite whatever settings (including adding/removing preprocessor symbols), and you just switch between which profile you want active atm.
I guess you could say "Unity should automatically create 3 build profiles (dev/prerelease/release) for me, each with symbols already set" but ๐คท, feels like something very minor.
To me "clicking creating a build profile and clicking adding a symbol" is pretty minor, and this is an one time thing per project so it's not like you have to do this on every build, but I guess we have different definitions of minor.
something used for most projects isnt a minor thing to miss IMO
There's DEVELOPMENT_BUILD. Never found a need for anything else.
"Most" projects here is definitely a stretch, and you'll find there are a lot more things you think are common that arent implemented. This really is a minor thing
there isnt one project where i didnt had to strip stuff out between debug and shipping builds
That's what the DEVELOPMENT_BUILD flag is for though
is it always defined ? or only defined & true when building with the dev flag is checked
It's defined in the editor and when the "development build" checkbox is checked
yeah im used for common things not being implemented ๐
so i can safely assume that !DEVELOPMENT_BUILD means shipping/release build ?
Yep
nice, thanks
best PL for android for me is Java, not kotlin.
-# PL : Programming Language
the best PL for .exe apps for me is C++ (C if needed)
best PL for scripts for me is python
yall agree or not?
Is there a point to this?
yes, knowing the ideal PL for situations
well this is a unity discord so c# is probably a good pick
C# is the best for games, i was talking about programs
c# is the best for unity
actually C# is way easier than C/C++
and still as practical as Java
i will go to #๐ปโunity-talk
thx
๐
idk why people always have this ego battle over programming languages
just use whatever the fuck fits best the task and shut the fuck up
you dont see doctors using butter knives for surgery
Probably a better comparison - doctors don't get dogmatic about the brand stenciled onto their scalpel handles
If it's sharp and sterile it's gonna do fine
Their hospital might have some sort of brand deal where they get all their equipment from one manufacturer, which means the doctors there use that one
but no one should have any sort of loyalty to it
It's pretty clearly a joke given their next message. Most people actually dont have this ego. It's really just university students or people who haven't been exposed to different aspects of development
The only real programming language is machine code anyway
Just make your entire game in assembly like Chris Sawyer and then you have no problems
Does anybody know how the made the character in Enter the gungoen rotate so smoothly and feel like they have a frame for all 360ยฐ of rotation. Especially the gun and how it rotatet and animated?
Hello dearest unity community! Im using the tarodevs playerController in case you know that, and im trying to implement moving platforms (without parenting the player) and if tried it via calculating the platform velocity, and than syncing that to the player velocity, but thats just making my player shoot of the platform, all attempts at moving the player via transform or rb.transform resultet in jittering and im kinda going insane.. maybe someone had this issue before or can help me!
wait ill upload my crazy spgagetti modified version of the playercontroller anyways
in case anyone has tipps on improving the readability of my code hit me up, cause i feel like even tho ive tried my best to keep this clean it is getting out of hand once again
why dont you want to parent the player?
it creates some CRAZY visual buggs and jitteryness and something with the local and world position is wildy going wrong
also i feel like parenting the player to the platform might create other problems later on, but maybe i gotta fix the parenting thing
the player is strechting everywhere and than stars glitching into walls when parented to the platform lol
i hate being stupid๐ give me etheral knowledge please
Well I didn't want to debate what the best programming language was so I decided to say something ridiculous instead ๐
If someone had taken the bait and started a crusade over it that would've been an added bonus
just add the velocity of the plattform to the players velocity
yea i took the bait
hope you had a good laugh
xD
guys I need help whenever I change values in inspector while in or out play it doesnt show any changes in the unity engine even after iu play or mid play
can you show us a vid
You probably have code changing them after you start the game
wdym
here is the code
I mean you probably have code changing them after you start the game
!code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
What variables are changing when you enter play mode
...the question you asked
I am asking you which things are doing that thing you said they were doing
You should probably consider reading messages instead of just instinctively typing "wdym" to everything
I think nothing changed BUT when I try to change them and regenerate the world it doesnt make any update it doesnt update it any ay
like in the inspector th vars are changed but they make no difference
for example when I change humidity of a biome it should move it, but when I change it it stays the same
Have you put any debug logs in your functions to make sure they're running at all
I dont think so
then do that first
See if the code even reaches where you're expecting it to do things
โ๏ธ ๐ Another Philosophical Best Practice Question: ๐ โ๏ธ
I'm designing a character animator whose animations need to be changed as the character moves around the arena. I can't use input values, because the directional input from the player will rarely match the local directions of the character on the screen (the camera is set at an angle, and the character often rotates to face other characters). So the CharacterAnimator needs the value of the character's "local" move direction. I see two philosophies here:
- The CharacterAnimator should fetch the move direction of the character, so it grabs an instance of the RobotController and queries the RobotController for the moveDir of the robot.
- The CharacterAnimator should allow objects to give it the robot's direction. So it creates a public method called "UpdateMoveDir" which the RobotController calls every frame to pass in the moveDir.
Can someone talk me through the two philosophies, and how they make/break best practice when it comes to object responsibility and performance?
Personally, I think the latter approach might become a bit of a nightmare to manage if you have objects close to eachother that can both affect the players movement, or objects that affect the movement in opposing ways (one moves it left, and another moves it right, keeping the player in a weird "undecicive" state) - for that reason, I think the player should determine their own movement in the world, rather than the world determining the players movement - the player could use raycasting/physics queries like a spherecast to figure out if things around it should affect when it should stop or something
In the former approach, I dont think I understand the issue of updating animation variables to affect the animations that play, regardless of the input thats coming from, if those values are between 0 and 1, you can treat movement like a percentage or convert the input into local direction: https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Transform.TransformDirection.html
Yeah for option 2, my idea was that only the RobotController would call those methods. But even so, the idea of making a method public for a single external class to call it feels like a magnet for possible issues. Especially given that the object should really only have one animation state at any one time.
My brain is processing the second bit - "covert input into location direction" I think I understand what you're saying though I think I'd need to use InverseTransformDirection if I'm not mistaken. Because it's a top-down game, I need to convert world coordinates (W means "move this direction in the world") to local coordinates, because the local coordinates would determine whether the player is strafing, moving forward, backward, etc.
Yeah imo I think systems should try to be as independent as they can be, so if they dont need to have public functions which change the logic, from other classes accessing it, its probably a good idea to keep it local - you can try inverse if you think it will be better for your situation, its nice that the API provides a few different options for converting vectors, and if needed, you can also flip the sign of the resulting vector
I'm trying to code a dialogue system for my game
a conversation is a list of lines, and each line holds needed information, like the plaintext of the message, whether it's incoming or outgoing, etc
Im struggling to decide how to store the pointer to the next dialogue line
In some cases, the next line will be set, in which case, easy. Next line is the next line in the list.
In some cases, I want to be able to randomly select one line of several
In some cases I need to select a line based on game state like amount of ammo remaining or something
In some cases I need to prompt the player to choose one of a few responses
unsure how to fold all of those cases together
It needs to be a graph or tree structure basically.
You can try using an existing framework like NodeCanvas or build your own
I'm trying to figure out how to build my own, my dialogue system is convoluted and morse code based and part of the primary gameplay loop, so a plug and play prebuilt framework wont work in my use case
Trying to figure out how to allow the same system to handle the different cases of how to proceed
Considering making like, an enumerator, with
- set
- random
- conditional
- playerChoice
unsure if a two-part system, with type and list of options stored seperately, is my best play
the simplest way without making a complex system would probably just be through scriptable objects, each asset represents a line. Each instance has a list for next possible lines. Use an enum/inheritance to determine how the next one is decided
NodeCanvas is far from plug and play
I have a basic concept of how to acheive that with enums, how would I use inheritance to do that?
basically just to override the method for how the next line is chosen, in the case of the ammo or letting the player choose.
if you use an enum, that "conditional" part you mentioned above would have to constantly be updated to handle new cases. if you use a base class and override the method it'll be a bit cleaner.
Though if this system grows large i can imagine it being a nightmare to see the graph here. You'd probably want some editor script to draw it for you
and then we add more features like editing it from the graph and you've built a complex system!
public class Line : ScriptableObject
{
public string plaintext;
public messageDirection direction;
public List<Line> nextLines = new List<Line>();
public nextLineType nextLineType;
}```
How can I make it so when I hit the plus sign to add a new line to the conversation, it allows me to edit the lines from the same inspector rather than prompting me to drop in a line item?
desired result is something like this
you'd probably have to write editor code to do this. otherwise this wouldnt be a scriptable object
there is a attribute you could use with SOs naughty
or yeah custom editor code
hello does anyone know how to load levels in unity
Like i have a map with 3 levels
i want to load level 1 when this happens, do i use different scenes? or what
Ahh, I see, thank you
help someone on this
be patient its been 5 mins lol
also this is a #๐ปโcode-beginner question
you'd need to learn how the SceneManager works btw
I told you how, you call LoadScene with SceneManager
if you want to split it across different levels thats up to you and a game design question
so i can make one scene for each level, and i just have to add my player each time into each scene at the spawn position where i want it?
i think i understood it that makes alot of sense
yes unless the same player is passed through the scenes each time or use ddol but those are diff topics
depends how you handle data
ye i understand what u mean
lowkey sounds way simpler then i overthought and overcomplicated that
data saving shouldnt be too hard
i found a way to handle that
but i just need to reuse the same player
or use tags
use tags for what?
make a complete sentence before you hit send
finish a thought, then hit enter
habit sorry
hey,
Why does it say that instantiateParameters are never used while I use it to get the parent in the Instantiate method at line 99 please ?
the errors tells you why, you only assign something to it but you are never actually using this variable for anything
but I do at line 99 in the "Instantiate()" ๐ฅฒ
you're assigning to it, not reading from it
Oh, then that type of warning is stupid, how can I remove it please ?
why even have that object if you're not gonna use it
thats what its trying to tell you, its not a stupid warning..
I forgot why I have that ๐
Oh yeah I wanted to instantiate my tiles and have the parent be the gameObject "canvasCenter", and it complained and the solution I found was the InstantiateParameters as it was the thing it suggested if I remeber correctly
nope, Rider itself
if you want them to spawn as child of canvasCenter then just put that there, there is no reason to have instantiateParameters cause Transform itself is one of the parameters of instantiate
Oh yeah, I took the first signature proposed here
So why does that thing exist ? ๐ค
This structure is used in Object.Instantiate and Object.InstantiateAsync in order to provide maximum flexibility in the parameters you provide. It has the added benefit of unifying the meaning of the parameters in both methods.
https://docs.unity3d.com/6000.1/Documentation/ScriptReference/InstantiateParameters.html
its just them making a fancy struct for them so you don't have a big signature/method
I have no clue of what "benefit of unifying the meaning of the parameters in both methods" mean here ๐ฌ
Who's "them" ?
the people who work on the engine, Unity devs
oh ok, thanks ๐
this is a unity 2022+ thing i think. fairly new
I have another question, the IDE keeps suggesting me to use the keyword "var" instead of the type itself, is there a good reason of using "var" over the real type inside method, loops, etc... ?
oh var is quicker than typing the full type sometimes
https://www.jetbrains.com/help/rider/SuggestVarOrType_SimpleTypes.html
you can literally look up the inspection information to see why it may be suggested
Ok so do you both recommend it ?
i personally use var rather than explicit types for local variables. but it's really a personal preference thing. just figure out what you prefer and stick to that
Ok ๐
its easy if you can tell what type it is right away
var mything = new Vector3(1,2,3)
I already know var here is Vector3 cause its right there in assignment and so on
mhh
sometimes without ide var is hard to tell what type it could be if you got a chain of stuff going on and bad variable names lol
var mything = someThing.thenAnother
what is var? we dont know without Ide hover / display next to the code
For some reason my tiles don't instantiate in a grid anymore and I don't understand why ๐ค
The code :
public void GenerateGrid()
{
for (int i = 0; i < GRID_WIDTH; i++) {
for (int j = 0; j < GRID_HEIGHT; j++) {
grid[i, j] = 0;
Tile tile = Instantiate(tilePrefab, new Vector3(i * TILE_SIZE.x, j * TILE_SIZE.y, 0), Quaternion.identity, canvasCenter);
tiles[i, j] = tile;
tile.Value = grid[i, j];
}
}
}
Check the value of TILE_SIZE
did you try adjust size of gridlayout ? thats pretty much putting tiles wherever it wants i think
Also check if you have a layout group on the parent
nope, no layout group on the parent
But how do I make it like take the size from my code, i.e my variable TILE_SIZE
no matter what you put there the canvas group is changing all the tiles to 100x100 with spacing of 0,0 . look at bottom section of Layoutgroup
also are tiles actual Image component btw?
and if the layoutgroup recttransform is 100,100 as shown in picture thats why its putting them all in a single column
layout group is weird to use if you're doing a board of tiles with your custom code
There's clearly a GridLayoutGroup in your screenshot
But yeah why use the GLG if you want to position them in your code. Pick one or the other.
Ah, thought when you said "parent" you meant the parent of "CanvasCenter".
Ok, I'm gonna choose to let the grid layout group handle the positioning for me but how do I make it understand to :
1 - Use the size of tile from the code
2 - Use the GRID_WIDTH and GRID_HEIGHT variables to understand how many Tiles there should be per line and per column ?
Or if you have a better way / the best way of doing things like that
hey there can anyone help me. I am trying to make flying enemies in unity and I do not know how to make them with the current graph agent system does anyone know how to?
grid layout group is set to "flexible" so its based on its Width rect transform, so you'd need width = tilewidith + offset x grid width count size
argh, so I can't make it adapt to different width and height grid size ๐ฌ
are you commenting on what I said or what someone else said just wondering?
its a pain in the ass to use layoutgroup for this tbh, just keep it all in the code.. Is there a reason you're using UI and not spriterenderer btw?
someone else
just use the aaron berg A* pathfinding
pretty sure brackys or something made a tutorial on this
I'm using an image for the background of the tile and a text for the number on the tile (It's a Minesweeper game) for the number of mines around the tile, then I will also add an image for the mine as right now the mines are represented by "-1" in the code
oh really
i did not know that let me check it out
doesnt really answer the question lol
I don't think Brackeys use the "agent system" as his videos are really old
Oh yes but I forgot why
okay well I would just skip the layoutgroup
personally I wouldve done this with spriterenderers not UI
then how would you center everything ? I think that was the main issue because it was always in the bottom left ๐ฌ
by UI you mean "Image" ?
because you were probably starting positioning from vector.zero at world pos
btw I cannot find the brackeys tutorial on A* pathfinding if you have can you possibly send it?
Let's learn how to make 2D pathfinding using A* with and without code!
โ Check out Skillshare! http://skl.sh/brackeys17
โ A* Pathfinding Project: https://arongranberg.com/astar/
ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท...
does this also work for 3d?
Image / Canvas yes.
the plugin itself yes, flying enemies thats tricky..
normally you would not use navmesh for flying enemies for 3D
Ok let me change that to spriterenderes
you would do something like an Octrees so you can properly a* it @fresh bay
if you do that you have to keep in mind you're no longer in cavas, and should not be in canvas and object are actually placed infront of camera
I think he's doing an AI in the air, so I don't know if pathfind works the same in air compared to on the ground
ah, but my game is 2D, so what's the purpose of Canva if I can't use it in this case ? ๐
like I said, for AIR navigation in 3D you need Octrees
2D or 3D has 0 to do with canvas, canvas is mainly for UI elements by default the canvas is Overlayed ontop of the camera so you can put that camera anywhere and you still see UI
SpriteRenders are most common used with 2D games cause it literally just displays 2D sprites.. The only difference these work how a stage play works in front of the camera
the benefit of UI is scales with the screen if chosen to do so, which may or may not be wanted..
spriterenderer stays same size relies on orthographic size for "zoom" of camera and viewport size how much camera can see
from what i hear Canvas is less performant when it has a lot of changing elements to draw
But in my case I want my tiles to adapt to the screensize, otherwise I will have small tiles on big screen for instance
usually its not a problem if you correctly place them with good ortho size and good aspect ratio in game view to preview what it will look like.
anyway dealing with rect transform will be a slightly different also dealing with anchor positions
pick one and stick to it, the code itself doesn't change much
the grid layout group can be skipped
How do I remove the canvas being the parent of my tile in this prefab ?