#archived-code-general
1 messages · Page 285 of 1
makes sense
so since its another gameobject it doesnt destroy with the destroy(GameObject)
ty my man
you are really helping me
np !
you spent the last hour here with me and helping without even knowing me
cheers for more people like you on the world!
one last thing if i may
sure
im setting it as color and it says it is ambiguous between system.drawing.color and UnityEngine.Color
i literally just did ctrl c ctrl v because im honestly fed up with my nonsense XD
yes you must remove the namespace cause right now it has both and its confusing the compiler
its the editor auto-adding namespace
the namespace ?
those using statements up top
yep
those are namespaces
but i dont have those
think of them like folders your scripts belong to
yes yes
delete the system.drawing one
since it has a Color inside of it
the computer doesn't know which Color you want, from UnityEngine or System.Drawing
usually visual studio does that when you paste code
you can delete all the dark gray ones
could disable that feature for paste if you'd like
hmm idk it could be usefull in future moments right ?
it just made me f up because i was lazy
i think
sure just be aware of it
Hello! this may be a really obvious question but I cannot figure it out for the life of me var projection = Vector3.Project(vectorOfTarget, transform.right); I have this projection and I just need to get the length of it. Does anyone know how?
(hope i dont have to ask again for help xd)
magnitude iirc
oh it is, ok in that case I have another problem lmao. I'm trying to make a tank rotate so that its bullet will hit a player if it is moving in a constant direction.
private void RotateToShootPlayer()
{
Vector2 direction = player.transform.position - transform.position;
var vectorOfTarget = player.GetComponent<Rigidbody2D>().velocity;
var projection = Vector3.Project(vectorOfTarget, transform.right);
var vectorOfProjectile = transform.right * 12f;
float angle = (Mathf.Atan2(direction.y, direction.x) + Mathf.Asin(projection.magnitude / vectorOfProjectile.magnitude)) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(Vector3.forward * angle);
}```
This is my code so far and it's so close to working but there is just something I am not doing right and I can't see it
are you just trying to do rotatetowards
no, here is an image of what i am trying to achieve
like prediction
well its not really a prediction it can be done by a calculation im just doing it wrong
You can figure out the angle the tank needs to rotate using trigonometry but that is only if the player is moving at a 90 degree angle so you have to project the players direction onto a vector at 90 degrees then use that projection in the calculation but im doing it wrong somehow
my trig math is kinda dogshit sorry 
made a tank game myself 2 days ago my enemy just shoots directly at you lol
yeah, unfortunately I have to do this for a uni assignment 😭
Show a video of what it does currently
it just follows the player exactly
one of those things you'd find on stackoverflow
yeah I've searched everywhere and can't find a solution
@stoic mural this is pretty simple task logically
First you calculate "predicted position of player when the bullet will reach him"
Let's call this position predictedPos
Now all you have to do is transform.rotateTowards and give predictedPos as parameter
The hardest part here is just to count where player will be when bullet reaches him
Yeah, for my task the bullet has to be 100% accurate. It can never miss
yeah thats what im trying to do using trigonometry and projecting the players movement transform but it isn't working
Projectile motion and interception gives a lot of good answers and SO does seem to have a lot of posts about it
I have to use the players location, and velocity and use it to get a clockwise angle in degrees. That is the way I need to code it. All of the stuff on SO doesn't do that and they calculate the position that the player will be in over time then just make the projectile go towards that position.
What's the problem with that approach from SO? That's kinda how you go it and why they did it like this 😅
It is for a university brief, I need to do it in the way they tell me
And what exactly did they tell you?
Shots aimed at the player should hit if the player is not moving, or if the player is moving at a constant speed. To avoid hits, the player must need to change while the shot is travelling. As input to the system you will be given the player’s relative location and velocity. You must return the relative clockwise angle in degrees needed to hit the player.
So, what SO does and then you convert it to some degrees 🤷♂️
where can I ask for help with something in Unity?
It's always a question of degrees to shoot at position P. If player not moving- P is player pos. If player moving - do what SO does to find where you can hit the player - that's your P. Return degrees to be rotated at P.
Pretty much any channel #🔎┃find-a-channel
Depends on what you need help with
This is obviously a code channel, so it's for programming issues
you will also need to use the projectile velocity to calculate this
transform.right * 12f is the projectiles velocity
var vectorOfProjectile = transform.right * 12f;
Okay, so for my game's main fighting screen, the enemies (all of them are bosses) come one at a time, and a new one only comes after the previous enemy is defeated. Because they come one at a time, is there a need to try using scriptable objects for their stats?
is the velocity the distance the projectile has to travel?
(to do this trig algebraically it would be helpful to introduce a variable for time)
Probably gonna want to actually get the velocity or calculate it instead of using a magic number like that.
Is there a need? No. Would it be useful? Sure
I'll also admit, in regards to my question, I have no idea how to really use scriptable objects for stats for enemies, so I'll probably be asking a lot more questions about that.
SOs would be very helpful in having boss varieties
It's just an asset file.
You create the Scriptable Object script with the fields you want. Then in the project window, you create an instance for each boss and fill in the values
Then on the boss class script, it would have a field for the scriptable object, and you drag its specific stats SO into that field
Then the boss uses that SO to populate the data in its class
Okay, I think I understand a little better.
You do not want to modify the values of the SO at runtime
It's not a magic number
{
tank = GameObject.FindGameObjectWithTag("Tank");
rb = GetComponent<Rigidbody2D>(); // Gets the rigid body of the bullet.
rb.velocity = tank.transform.right * 12; // Applies the velocity to the bullet towards the players position.
}```
its what i set the velocity of the projectile to
I was asking because the fighting for the main bosses will be rather primitive, simply attack, they attack, you both heal according to your magic stat at the end of the turn, it isn't like a more fleshed-out system.
A magic number is using a number instead of a variable. You have 12 on that line, which is a magic number
I'm looking at the fighting of gods from ITRTG as an example for the combat.
Yeah i have it in a variable called force but would it make any difference?
Just do what SO says to find where projectile would hit the player 😋
In making it less brittle, yeah? That number only works in that one case...
it is the only case I need it to work in
I can't make any sense out of it
Hence why im here lmao...
Ok, fair enough. A basic programming principle is just to never use magic numbers, so that's why I pointed it out
Yeah, im just trying to get it to at least just work at the moment so I'm just cutting as many corners as I can
Well, target is moving and bullet is also moving... to find where one will hit the other, you need to solve an equation on t (t being time) where PlayerPos + PlayerVelocity * T = BulletStartPos + BulletVelocity * T
But you don't actually have BulletVelocity... you have its length and that's the part that you need if you do what the SO answer says. You basically are aiming at finding this T and where player is as that time, because that's a place that both the player and bullet will reach in T time.
Does that help making some sense out of it?
he does have bullet velocity, it's 12 units/s
the velocity of the bullet is the tanks transform.right * 12f
here transform.right is dependent on the value you are trying to calculate, so you'll need to be a bit more careful
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To 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.
you don't know that velocity, yeah, you know the speed, but not the direction, that's what you're trying to calculate
I'm trying to calculate the angle in degrees to rotate the tank in order for it to shoot the bullet striaght and hit the player along its course
Trying out some scriptable objects for boss data. How does this look so far? (also sorry if I'm not formatting this correctly.)
'''cs
void Start()
{
bosscurrentHP = bossMaxHP;
}
// Update is called once per frame
void Update()
{
bosscurrentHP = Mathf.Clamp(bosscurrentHP, 0, bossMaxHP);
}
'''
actually... you need the second answer from that SO link... I think it's better explained...
transform.right is the local direction when the tank is already rotated at the correct angle - the angle you are trying to find
So what do I need to do in order to solve that?
What I'm trying to go for here is, when starting, each boss's current health is set to their maximum, and that their current health cannot go below 0 or above their max health. I can set it above the maximum health in the editor, but will this code still work?
Again, I'm not good with scriptable objects at the moment, so sorry if this is a silly question.
Hi! how can i make a boat system where you gotta pull the rope in the boats motor it will start the engine?
if someone knows pls tag me to the answer
there's a stackoverflow link that has a full solution if you just want that, but otherwise you're getting hints about what to think about to get you on the right track but you kind of seem to be ignoring them
you'll need to switch your brain on at some point and really think about the problem to get an understanding of it
again, the SO link is making 0 sense to me which is why im asking here
I am not ignoring them I just do not understand properly
I am trying my hardest to understand what I am reading but I have been working on this problem for over 7 hours straight now
if you figure out the angle to fire at, your rotation of degrees is the difference of your forward direction and the direction to aim it at
I mean, Pulni typed out a pretty great summary of what to think about here: https://discordapp.com/channels/489222168727519232/763495187787677697/1216283403171790959 but you just completely glossed over it
Sorry, but what you have there now makes little to no sense
Okay, so how can I make it better?
You have to learn what scriptable objects are and how they work. For example https://learn.unity.com/tutorial/introduction-to-scriptable-objects
I didn't really understand it.
sin a = o/h
Although we don't know the length of o or h as they each depend upon the variable time, we can still find the ratio. If we say:
v = speed of target
p = speed of projectile
t = time
then:
o = tv
h = tp
so:
sin a = tv/tp = v/p
and, as you can see, the time variables cancel out. What this tells us is that the angle calculation does not depend on the time.
Re-arranging this we can find the angle with:
a = arcsin v/p
The Unity function Mathf.Asin will perform this calculation.
This solves the simplest case, but in practice, the target is unlikely to be moving at exactly 90 degrees. However, in general, we can project the target's direction vector onto a vector at 90 degrees and use the length of this projection as our value for o.
If we can create this projection, then the solution is the same as the simple case above. The Unity function Vector.Project will create such a projection.
If the target is not directly ahead, the we can rotate our tank until it is. And again, the solution is the same as above.```
I found this and tried to do what it is saying as best I can but I am going wrong somewhere.
I'm not sure where you found this but it looks very wrong to me
It is at least somewhat wrong I think, yeah... misses some cases at the very least 🤔 (or perhaps only works in some cases is a better way to put it)
Found it on my uni site, lecturer uploaded it to help figure out the solution.
that's disappointing to hear tbh
i mean it obviously works for what they want, the course has been running for years and students before me have tried and succeeded with it
I think the clue is in the very last note - you have to rotate the tank first, and do this in multiple steps
fully leveraging Unity to do the work for you
Yeah, I'm trying to rack my brain around the SO right now. When they say "the targets vector" that is referring to the targets velocity right?
yes... but also Deynai's point about the very last note in the text from your uni is a good one 🙂 that's what you're missing in your code to make it work (if that whole approach works... which perhaps it does, even though it seems weird)
I've been looking around a bunch for tutorials and I'm still not understanding how I can make this work how I want it to work. Maybe I should try another method, because I've been bashing my head into a wall, metaphorically speaking.
Unless I'm just not thinking about it right.
it looks like they have normalised it, so the vector V0 is velocity.normalized and the speed s0 is velocity.magnitude
Yeah, just not sure how exactly I would do that? It does seem a lot more difficult than trying to understand the SO link tbh lmao
Well, the problem with your code is that you're projecting on tank.right... you should instead project on direction from tank to player, normalized, rotated 90 degrees clockwise (I think clockwise, not sure), so, perpendicular to the direction from tank to player... which you can calculate manually, or you can set the tank.up to the direction to player, and then project on tank.right
yeah it doesn't work, but for a fast projectile it's an approximation that's probably good enough
Tried to do what SO said and still doesn't do what I want
I think what is happening now is that it is shooting behind the player and not infront
there's at least one mistake in the algebra from the top reply unfortunately
Does anyone have tips for making enemy stats work in scriptable objects? I keep trying to wrap my head around them but I’m getting nowhere.
Maybe I just need to sleep and try again. I’ll ask later once I’m well-rested.
[CreateAssetMenu(fileName = "New Entity Profile", menuName = "Entity")]
public class EntitySO : ScriptableObject
{
//Entity Info
[field: SerializeField] public string Name { get; private set; }
[field: SerializeField] public Sprite Sprite { get; private set; }
[field: SerializeField] public Animation Animation { get; private set; }
//Base Stats
[field: SerializeField] public float Health { get; private set; }
[field: SerializeField] public float Mana { get; private set; }
[field: SerializeField] public float Speed { get; private set; }
}```
How can i fix this? this is my throw code;
if (Input.GetMouseButtonDown(0)) {
rb.isKinematic = false;
interactBase.haveParent = false;
rb.AddForce(transform.forward * throwForce, ForceMode.Impulse);
transform.SetParent(null);
didThrow = Teacher.Instance.isTeacherAngry;
}
Does anyone know why EditorLoop spikes every second (pretty much exactly)?
It's making up 98.2% of the frame and it's on the exact frames my game freezes for about half a second
This is a completely empty project with an action based XR controller and a quad
Okay great nevermind it was because I had something highlighted in the inspector...
Has anybody got any ideas on how to fix this?
_body.position -= leftHand.localPosition - lastLeftPosition; I'm using this line in update to move the body by how far the hand has travelled so it looks like you're grabbing something. Issue being that it's jittery. Not noticably but it is jittery
I thought of using lerp to interpolate the movement but that would cause it to not be exact and therefore cause a desync
I have a major problem. I have an abstract class for controlling menus, and a pause menu that derives from it, but when I start my scene, which has a pause menu derived from the abstract menu, it, for some reason, removes the variables that are added in the derived class.
Is this just how abstract classes work, or has something gone wrong here?
something gone wrong... show what you mean in video or screenshots
Here is my Abstract Class
https://pastebin.com/3yiFHj5T
And here is the Derived Class from it (The disappearing Variables are in the image screenshots)
https://pastebin.com/WFL0gnyy
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
In the screenshots, it shows how, in editor,, all the variables look fine, but as soon as the scene starts, they all disappear, and malfunctions occur
Can I just not add variables to the derived classes of Abstracts?
wait, are the variables disappearing in the inspector? not just heir values, but the variables themselves? when you enter play mode? 😮
I have no clue, but SOMETHING is breaking, I'm doing more investigations, it... Might just be an editor bug?
The variables inconsistently appear in editor during play mode...
I'd say restart Unity just in case
right after you start it, check if you have any errors in console
and whether the stuff appears
Oh, no, it turns out, I'm just stupid. Apologies, I accidentally didn't have my "enable/disable" menu inside of the code that actually made it activate when the menu finished sliding on/offscreen.
That, paired with the editor acting weird, convinced me that something was going on.
Hello everyone, first of all is the first time I try to do something like this and I need help on a specific thing, I'm trying to recreate the kinetic rotation system of the create mod of minecraft, but I have a problem, I have been able to make it transmit the blocks connected by a boolean system but I would like to make it can transmit the speed of an engine or an object that can vary, ie an engine with a certain variable speed by the player to change the entire sequence connected to the network and even if there is a block that changes this speed in the middle of the network, then also change it for the following blocks. The problem is that I do not know how to make the block a transmit the information to block b, and block b to c... etc. I have this code, does anyone have an idea of how to do it? I would be very grateful. I leave a video so you can see what I mean with the rotation system if someone has not played the create mod
hi, please share your code in a paste site. it'll be easier to read than screenshots
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To 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.
thx fr the help btw
what is the best way to store variables/data such as scores between scenes? I utilize playerprefs right
Static class, Singleton/DDOL, ScriptableObject. All are preferable to PlayerPrefs
why is my player not being found?
GameObject is not component iirc
and you probably can reference it in inspector directly
even without that it still cant find it
Hey, I am looking to some kind of comparison/juxtaposition of old vs new unity systems. Not necessarily a comparison of features (but would be nice), but just a comparison of what system corresponds to what other system. I'm trying to google for something like "new vs old systems in unity" but it doesn't really give meaningful answers :P
Some things (I think) I already understand
MonoBehaviors/Components -> DOTS ECS
Old input system -> new input system
old unity UI -> new UI Toolkit
Asset Bundles -> Addressables
BRP -> URP/SRP/HDRP
did I get it (generally) right and are there other examples (of legacy vs new things, even if they are still not fully supported)?
hi
im trying to loop a 10 sec video from the 6th sec mark. Anyway I can make the loop be seamless without any pause? Here's my code
using UnityEngine;
using UnityEngine.Video;
public class VideoLoop : MonoBehaviour
{
[SerializeField] VideoPlayer videoPlayer;
void Start()
{
videoPlayer.loopPointReached += Loop;
videoPlayer.Play();videoPlayer.playbackSpeed = 1f; } public void Loop(VideoPlayer source) { videoPlayer.Play(); videoPlayer.time = 6f; }}
hi, im having an issue. I made a Fullscreen script for the editor, but when i put it in the resolution of my mac, M2 macbook pro. it doesn't cuts a part of it and just glitches out :/ weird af.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
what is a good way to represent a bunch of menus that overlay on each other in terms of data?
I feel like a Stack makes sense, but Stacks aren’t very good at peeking in the middle, or chopping the stack from the middle.
Like final fantasy menus that overlay on each other like main fight menu > magic menu > target select menu
Are you asking performance-wise or what?
architecture wise
i always stress when I add new menus to my system, and it makes me sad
i want to be able to easily define new menus, and define the connectivity without a bunch of switch statement nonsense
and every time I try, I end up with a system that still sucks to extend
A system like browser history, where each menu is basically a new page and a button opening a new menu is just telling the browser to navigate to a new page, is actually not very complicated to build.
It's not very common for game menus to get that complex though.
can someone let me know why the navmesh agent isnt moving? and why is it flickering so much? is having the .setdestination method in update wrong?
I currently have a tree-like hierarchy defined for menus. Each menu state is a unique enum value, and the hierarchy lets me know what is supposed to be under it.
And then I added a notification textbox that should be allowed over any other UI state, and it all went to shit
You have an animator with root motion enabled
That will fight with the agent
nope turns out having the ai function in update is wrong. but whats with the root motion animation?
Part of the reason for the hierarchy is to know: which menus not to disable because they are still supposed to be under, and define which menu states are allowed to go to which ones.
Root motion tries to move the root object, your navmesh agent is trying to do the same
Are you saying you fixed it?
Currently you are modeling your UI in the way of "A belongs to B" which is a fine way if it fits what your UI is like, but the web way ("A, B, C, etc are all independent, and they simply link to each other") also has its advantages, one of them being pages are highly independent and modifying one does not mean you need to go modify everywhere that's connected to it.
i had something like that, where I manually defined every link like a giant directed graph
but it quickly turned into defining a ton of directed links and switch statement cases and shit every time I added a new menu
That doesn't have to be the case
i know, but idk how to make a system that is not stupid
Link doesn't have to be a magic string identifier (like URL) or an enum containing every possible page, the link could just be a page factory or even the page itself.
it was basically a dictionary of <enum current state, enum[] states we can go to>
which, was not good
i feel like this is something that could be actually easily defined via visual scripting, to actually see the graph
I don't think it's necessary to use a graph at all
Okay, I added serialized fields for Max HP, current HP, name, sprite, attack, defense, and magic. Now I just plug them into a script?
it’s just a way for me to visualize. At the end of the day I need 2 things:
- Function of current UI state that spits out a bool for whether or not a given menu should be enabled or not
- A function of two UI states that spits out a bool for whether or not that transition is allowed or not
as long as I can define the functions in a way that allows new menus to be easily added, all is fine
In my project where there are hundreds of pages and they can navigate amongst each other, it's really simple: router takes care of navigation to a new page, backing to previous page, and transitioning/displaying the current page. A page is nothing more than an interface that implements specific things for router to use it. And a page going to a different page is simply Router.Push(new NextPageToGoTo(...));.
at the end of the day, that is similar to a directed graph
There's no complex graph dictating which page can go to what, no magic string, no giant enum containing all possible pages, no giant switch. If clicking this button is supposed to bring up a sub menu, just push it to the router.
it’s a function that can be represented as a directed graph, as opposed to a function that reads a data structure representing a directed graph.
Hmm well I might be missing the point why you need to explicitly define which menu can go to another menu, because to me menu A literally cannot go to menu B unless there's a button in menu A with code that explicitly says "router go to menu B"
but I think the way you define it is like, each page is a vertex, and all links on the page are a list of vertices you can reach from that page, which defines directed edges
it’s a level editor, and some controls need to stay enabled (or not) when going to different menus. This should function as an extra layer of protection against bad transitions
like if I press the wheel button while in the level save screen, I want the extra protection to block the wheel menu from popping up
since UI elements can majorly fuck everything up, I use it as an extra layer of redundancy for validation
Eh, the way I do it in my would just simply be router is the one listening to wheel button event (since router is the one controlling all of UI) and level save menu's router simply ignores all wheel events.
Which means if you are in level save menu and goes to a sub menu of level save, you still can't click open the wheel menu without you needing to explicitly code that into your logic.
right now I have a router that actually does transitions. Each menu has a separate set of Monobehaviours that call Router.RequestSetUIState(…) to ask nicely that the UI state be changed
Router asks UITransitionLogic to validate the transition as a condition of actually going through with it
I try to do this as well. But I fear I will inevitably miss some weird combo of inputs that will cause the UI to break.
That's exactly why you shouldn't do it like that ("validate transition is allowed or not")
i’m confused
Because that's essentially O(n^2), when you have n menus, every menu you need to write n-1 validations to say "is this transition allowed" and you will inevitably miss one or two.
yes, that is why I did not like the previous method
That's why wheel event should just get send to the router and router handle it.
but I’m doing that right now? Wheel menu recieves input, and sends the event to router, who is smarter than wheel menu
Level save menu has a router which does not handle wheel event, so that means when level save menu (and all of its sub menus) is active, all wheel events go to that router which get ignored. In another router where it is allowed, then wheel menu will get transitioned.
oh you mean to more manually make sure the modes of input get turned off?
No
I mean there are multiple different routers, the router used by level save menu simply ignores wheel events, where some other routers do allow wheel events and navigate to the wheel menu.
so let’s say I am in save menu, and click the button for wheel menu on my controller. In your system, are you saying the wheel menu does capture input, sends to router, and router ignores?
oh. i see
In my game the main router can handle deep links, whereas router for in game menus like pause screen ignores deep links. It's basically the same idea.
So instead of coding the logic of "pause menu cannot activate deep link" you move that logic into the router and becomes "in game router cannot activate deep link"
i have to think about that a bit more.
like how i’d refactor to connect everything
I have an idea, actually. My main method is RequestSetUIMode(GameUIType newMode)
I could change the signature to RequestSetUIMode(GameUIType newMode, GameUIType requestingUIMode)
so the second argument is the menu we are invoking from.
that defines a shallow link, and router rejects if the requestingUIMode does not match the current mode.
does that sound like a good idea?
Is GameUIType the giant enum that contains every type of menu, and the method does a giant switch on it to show the corresponding menu?
yes, and second is currently kind of yes
but proposed to be just if (requesting == current)
Yeah that gets painful real fast, every time you want to add a new menu you need to 1) obviously implement the menu itself, 2) add a new enum member, and 3) add a new branch in the method to handle that enum member to show the menu.
my current method, yes
- is a necessary evil no matter how you slice it
- is an awkward undesirable sideeffect
Use something like Router.Push(Func<IMenu> factory) (or even simply Router.Push(IMenu menu)), router just needs to know how to handle IMenu and that's it.
That way you get rid of 2 and 3.
oh so it’s an interface
Interface, a base class, whatever, some kind of contract.
i get that. But then I need an instance for each menu to request the router to go there
like a menu in the middle would need a ref to the instance of the IMenu it links to
Which you will need if you want to pass data between menus without relying on global state.
i'm watching a tutorial and I already don't like how uneccessarily complicated the code was made just for wasd controlls. can someone tell me if this code can be cleaned up and how i can add support for wired controllers?
using System.Collections.Generic;
using System.Numerics;
using Unity.Mathematics;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
// movement components
private CharacterController controller;
private Animator animator;
private float moveSpeed =4f;
// Start is called before the first frame update
void Start()
{
// get movement components
controller = GetComponent<CharacterController>();
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
//runs the function that handles all movement
Move();
}
public void Move()
{
//gets the horizontal and vertical inputs as numbers
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("vertical");
//direction in a normalized vector
Vector3 dir = new Vector3(horizontal, 0f, vertical).normalized;
Vector3 velocity = moveSpeed * Time.deltaTime * dir;
//check if there is movement
if(dir.magnitude >= 0.1f)
{
// look torwards that direction
transform.rotation = Quaternion.LookRotation(dir);
//move
controller.Move(velocity);
}
}
}
plus it gives me errors no one in the comment section has
if you want to support multiple controllers, InputSystem is very helpful
i literally defined a whole dualshock controller scheme yesterday in like 5 min, just adding it to everything else
ty, I will have to sketch it out a bit more
yup. thanks though
are you saying this code is overcomplicated?
because it is really not
i wish most of my classes could be as simple as this lmao
it seems to be because i have a message saying that "severity": 8, message": "'Quaternion' is an ambiguous reference between 'UnityEngine.Quaternion' and 'System.Numerics.Quaternion'",
you should not put physics commands in update btw
it says this for vector3 as well
why did you import system.numerics
because thats what the tutorial user did
nothing in this class needs System.Numerics
actually wait no they didnt somehow they got added after
that quaternion should be UnityEngine.Quaternion
Think about it with this example, when you type "burrito" into Google's search bar and hit enter, it goes to a new page, how does the new page know the thing you are searching? That data is passed in the URL with something like ?s=burrito.
The URL is essentially the argument of Router.Push() method, you use that argument to allow router to know which menu to show and what data it should have. It also means that your menus can be general purposed and reused in multiple scenarios, because now the pusher has the ability to feed different data into it.
idk where math or numerics came from considering i didnt add them. does VS code automatically add it when math is used?
visual studio has a feature to automatically add using statements, which is annoying as fuck. If you mistype something, it will look for a namespace that defines what you typed, and auto adds it to the top of the file
you need to turn that shit off. it’s in visual studio options
yup intellisense sometimes adds them when you use a function. its cool imo
ooh so it does! that is annoying AF i'm turning that shite off right now!
turn that shit off
it will sometimes add namespaces that break if you try to build your project
hell no its cool
oop nvm LMAO
a lot of times it added UnityEditor.…., and I don’t notice until I build, and like 10 files break
shit feature
you also get all these random namespaces at the top that you did not mean to use, have no idea what they are for, and now that they are in there, you don’t remember if you actually put it in or not on purpose because it’s been a month since you opened the file
and this time, it stopped his code from compiling because it created an ambiguity with a namespace he didn’t need
thats basically what happened. its been a week since i came back to it
happens every time
now i just need to find where in settings that feature is to turn it off
is this it?
That's for JavaScript/TypeScript not C#, and you are using VS Code not VS.
In VS Code this should be the one you want to turn off.
ahh ok, i was looking under statements, even intellisense and all sorts
As a general tip, look at the C# extension settings since the thing you are looking for is about C#.
will do in the future
VS Code's search bar also has a ton of filters you can use and you can type @ to bring them up, eg @ext: will allow you to filter only specific extensions.
for some reason unity decided to close itself so now i have to wait for it to open back up to test and see if my code works 😭
is deleting this folder (cache) going to screw me?
I presume its just stuff for quickload
i suspect that's the package manaegr cache
not familiar with where unity puts stuff on linux though
(also, not a code question; this should be in #💻┃unity-talk )
hello when ever i import a script it always says that the name is not corect when it is correct
because you have so many errors
but i only have 6
If 1 script has errors none of your scripts will compile
"only 6"
oh
In that script alone I count 4
I'm toggling on a UI canvas using a button and it works perfectly fine in editor, but as soon as I build the game, the button simply doesn't do anything. I've googled this for a while now and a lot of people seem to have a bunch of different small fixes for it (mostly relating to the Canvas Scaler settings), but none of them seem to work for me. I don't know if this is caused by how I'm toggling on the canvas or what and I'm stumped. Btw, all of this is being done in my script for Unity's lobby service, but here's a rough example of how I'm toggling on the canvas: https://hatebin.com/tdecricyjy
It's possible that the UI is sized differently in your build, and that something is covering up the button
Does the button visibly change when clicked, but not work? Or does it not respond to the cursor at all?
the button clicks normally
check if it's actually working by logging something in response to the click
then look at your player logs
yea it shows up normally
@heady iris ok so i was messing around with some of the player settings when building and i found out it only works if i use Fullscreen Mode: Maximized Window
everything else doesnt work
for some reason my ui canvas appears wonky when i move the camera up and down?
ok so i figured it out. apparently it wasnt working because i had two instances of the game open on my PC. as soon as i hosted the server from the unity editor instead of another built game, it worked fine. never realized it because i need to host the lobby for the join button to come up ofc
this shouldnt be an issue for the game itself tho cuz people are gonna be on different computers when playing multiplayer
Any clue as to why this is always returning false, even though a child wallcheck transform is clearly inside of terrain that is on the correct ground layer?
how is _groundLayer defined?
LayerMask
okay, good -- and I presume you've got the right layer in there
Same as my terrain yeah
OverlapCircle returns an array, that is never null - even if nothing was detected
I'd sanity check this by setting it to work with any layer
no, OverlapCircle returns a collider2D
OverlapCircleAll gives an array
(i'm finally doing a 2D project, so i know the methods now 😛 )
OverlapCircle also has an overload that puts the results into a list, which makes it more confusing
Right, this is very not much consistent with what OverlapSphere does, wtf
because this is 2D physics
it has different conventions
I wish 3D physics could put results into lists...
hello. i am new to unity. i have a sprite that is managed through shaders, and when i spawn an instance of the game object containing the sprite, i want to also set the shader's parameters to some initial values. but it does not work
Good advice, it seems it does not collide with ground layer but does with other layers, how strange..
Does a Physics2d call like that ignore stuff like colission matrix and box collider overrides?
The collision matrix is not relevant here
I'm not sure about collider overrides.
I would guess they don't matter, since you're just directly asking for things on certain layers
not for things that collide with certain layers
is there a way to get a rigid body on the parent from a child component's collider?
i don't think you can directly ask the collider
but GetComponentInParent will unambiguously give you the correct rigidbody
what if im not sure whether im getting the child or parent?
If your object has a Rigidbody, then GetComponentInParent will return it
It searches yourself and your parents
this func in the same script does work haha
like how GetComponentInChildren searches yourself and your children
i made a typo. "child OR parent"
so i have a collider on the parent aswell
but i dont control which of them returns first.
and i want to get the parent.
"which of them returns first"?
in the raycasthit array
I don't understand what you're doing
oh, you can just ask the RaycastHit for a rigidbody
True, tested this. The colission does not happen with ground but does happen with my room collider (enormous polygon so that makes sense)
it has a field for that
It will be null if there was no rigidbody involved
(also, even if you didn't have that, GetComponentInParent would give you the same thing)
how would there be a raycast hit without a rigid body?
a raycast can hit a static collider
no, "static collider" just means "a collider that isn't under a Rigidbody"
Having a rigidbody becomes important when you want to receive collision or trigger messages from collider overlaps
i was having issues with that originally. did i just have to configure the cast to check for colliders? cause when i last tried it it didn't detect my colliders and i had to use a rigidbody
i would note i both have a collider i need to cast and just normal ray casts
you can tell it whether or not it should hit trigger colliders
but having a rigidbody should not be relevant
It might have an effect if you've just moved an object with a collider on it
The physics system won't know about this until the next physics update
(or until you call Physics.SyncTransforms())
I dunno if having a rigidbody would change anything there
yeah. its so random sometimes. i don't even have that complicated of a setup, but i solved one of my issues by having a collider so im going to stick to it for now. thank you for letting me know i can get the rigidbody from a raycasthit result
When I add an assembly, Unity says InputAction does not exist inside the UnityEngine namespace?
What am I missing?
wdym "when you add an assembly"
Are you talking about the using directive
Your assembly definition will need to explicitly reference every assembly you need.
It won't automatically reference every existing assembly
you need to reference the input system assembly from your Gameplay assembly
Oh I see
I mean, the Gameplay assembly is the only one I made
So I'll need to make one for the input then
Is there a reason you're using an assembly definition?
Generation code too large, want to separate compile time from gameplay
your game doesn't compile when you enter play mode
oh, I see; you're saying that you have a ton of code for level generation, and you don't want to have to recompile it when you change your gameplay code?
in the assembly definition asset's inspector, reference every assembly you need here
Solved by the way, turns out a a overlapcircle like that does not work on composite tilemap colliders, so it can only connect to edges of the tilemap.
ty
interesting; i'm just starting to figure that stuff out myself :p
I didn't know the InputSystem had a whole assembly. I thought everything from Unity would be automatically referenced.
And only needed to reference custom assemblies.
yeah, what ill try for now is shooting a raycast to the left from the right wall check, distance being to the player, to see if a wall is in between.
Good to know thanks
There are quite a few assemblies. You can view all of them in the Solution Explorer in VSCode (and in something very similarly named in Visual Studio)
does nobody know this?
you're probably using a world space canvas
ive tried all the canvases
anyone know how i can check code for plagarisim
You sorta can't.
Code is meant to be plagarised. 🙂
If you're a teacher - give exams. If you're a student, you're cheating yourself (out of learning how to actually write code).
yh but they check plagarsim for code
Then don't plagarise?
i mean its not gonna be zero
I mean, it sounds like by asking the question.. you're probably doing something you shouldn't be, and you're not really gonna get any help with doing that here.
and ive used some help from outside sources so i wanna see the plagarsim
i just wwanna site that runs plagarsim checker
for code i dont think that an unreasonable question
If you've copied and pasted code you don't understand and can't explain well.. that's a pretty obvious case of plagarism.
Uh, yeah, it's a bit unreasonable and if you don't understand why.. your time might be better spent learning how to write code instead of learning how to copy and paste it and not get in trouble with your school. 🙂
is there a need for that smile emoji
so passive aggressive
🤷♂️
If you had wrote most of the code by yourself, you'd know that there's no point in ever using a plagiarism checker. Asking for one repeatedly suggests that this probably isn't the case and you did in fact just copy and paste a bigger chunk of code, maybe changed a few names here and there.
Either way, you'll know the results of running a plagiarism check on your code once you submit it to your teacher, if it's some sort of school assignment that we're talking about here.
Why when the method is run with OnBecameInvisible, then OnBecameVisible does not start, all colliders, there are renders on the mesh:
public class VisibleObject : MonoBehaviour
{
private Renderer meshRenderer;
private void Start()
{
meshRenderer = GetComponent<Renderer>();
}
private void OnBecameInvisible()
{
meshRenderer.enabled = false;
}
private void OnBecameVisible()
{
meshRenderer.enabled = true;
}
}
I do not understand your question.
how do i make it so i can drag in a game object into here
"then OnBecameVisible does not start,"
add a field of type GameObject
why
make it public or use [SerializeField] to make Unity serialize it
@wide dock He really needs to be ... trying to learn how to code from a class, not from tutorials.. ie, copying and pasting entire blocks of code and wondering why it won't compile.... #💻┃code-beginner message
I cannot understand your problem.
okay
Are you saying that the mesh renderer is being disabled, but is never becoming enabled?
That won't run if there are no enabled renderers on the same game object.
yes
The message is sent when a renderer becomes visible
You don't need to disable the renderer manually. OnBecameInvisible means by definition that the object isn't rendered
uhhh what
GameIsPaused isn't isGamePaused
and those look like they're on different objects/scripts entirely anyway
am stupid
is that a problem?
pause_music doesn't automatically have access to PauseMenu
When the program starts, the first message is sent, and after it becomes invisible and tries to become visible again, nothing works
yes, because there are no enabled renderers
so it is impossible for a renderer to become visible
think of your classes/scripts/gameobjects as houses.. or boxes.. your PauseMenu has a boolean called GameIsPaused but your pause_music (which is poorly named, btw?) isn't doesn't have access to it unless you tell it PauseMenu.GameIsPaused
ok ill just do it in the same script
Let's say, then why does an object need colliders if it uses them to disappear
colliders have nothing to do with OnBecameInvisible and OnBecameVisible
you don't need to but I'd strongly suggest taking a step back and understanding what "objects" are .. like, either from a professor or TA or something..
Or at least use the resources pinned in the code channels here and commit to properly understand the basics
Okay, got it
if i have a direction (0,1), and a incoming velocity (x,x). I want the velocity to become (x,1), so where direction is 0 velocity stays the same. How can i easily do this, or will i require if statements?
Vector3 result = Vector3.Scale(direction, incomingVelocity);
that sounds like the opposite, since that keeps the component from incomingVelocity if the direction has a 1
Oh wait you want the opposite of that?
just write a few ifs... 😄
Yeah but muh clean code
Scale with Vector3.one - your direction
it's not gonna be cleaner if you do hacky math that only you understand the meaning of
clean code is code you can easily understand
that Clean Code book has done so much damage to programming
(although that's hardly relevant here, lol)
i just bellyache about it
Hello, is this the right channel to ask for some help regarding coding?
TY
I have a problem when using cinemachine with spherical worlds. As in any game, i want the player to move in the direction the camera is pointing, so what i tried is to get the local rotation of the camera and paste the "y" component into the player's rotation. I use local rotation because since the player stands on spheres, it has to be aligned with the center of gravity. My solution creates a positive feedback loop where the player rotates, the cinemachine camera tries to follow the player's rotation, the camera's position changed so the player tries to follow it... I've been scouting internet but i couldn't find someone with the same problem regarding spherical worlds and camera controls.
You shouldn't directly manipulate euler angles.
First things first, you should NOT directly modify values of a quaternion by copy-pasting someof its compoenents here and there
(and especially don't modify rotation.y!)
If you want to do that, then prefer using directions (eg. .transform.forward), where modifying components is legal and its consequences predictable
Flatten using Vector3.ProjectOnPlane(), normalize, etc.
ohh okay, im new to unity so im just trying to get the squiggly red line go away 😅
If you have errors, you should post them, and the offending code in question
it is not an error per se, mostily a problem where idk how to get the player to rotate without making the cinemachine camera go crazy
The direction the camera is pointing towards is cam.transform.forward where cam is a variable containing the object which the Camera is on (or the Camera component itself).
I suppose you don't want to fly off if you look straight up and press forwards, so you'll need to flatten it along the ground. For that you'll need the ground's normal direction, ie. the direction that's perpendicular to the ground at a given point. If you're using a ground check that's using a Raycast in the code, then you can get the normal direction pretty easily with that
when making a font, is there a simple way to make a serialize strings to show characters like emojis or custom characters?
Hello guys. Maybe anyone knows how to download and save image in unity. I did but it cant be open. Or maybe i can change data format?
what filename did you save it as? What format is the image in?
yes you named it that way
but is it actually a PNG or not
where is this image coming from?
Access Google Drive with a Google account (for personal use) or Google Workspace account (for business use).
it is png actually
on google drive
That's your private google drive I can't access it
most likely your Unity client can't either unless you gave it authentication credentials too
i gave access
so i need to save it like jpg?
Cool. I gave access as you said and it is working now.
thx a lot
❤️
yeah probably because of the authetnication thing before
your URL would have just given a 403 error
Only started work with web in unity. Thx for help again.
This courotine is supposed to trigget the destruction sound and then deactivate the gameObject. However, the destruction sound doesn't play properly, the audio keeps on breaking up. How do i fix this?
private IEnumerator DeathCoroutine()
{
collider.enabled = false; //So the player's bullets no longer collide with the enemy
//transform.localScale = Vector3.zero; // This makes the Object invisible enemyHealth.
avatar.SetActive(false);
if (animator != null)
{
animator.speed = 0;
}
manaDeathParticles.Play();
audioSource.PlayOneShot(deathAudioClip);
if (healthType == EnemyHealthType.SpawnManager)
{
spawnManager.enabled = false;
}
yield return new WaitForSeconds(2); //This delay is here because otherwise the gameObject (and its audio source) will be set to inactive before the death effect can finish playing.
if (deathBehavior == Death.DestroyUponDeath)
{
Destroy(gameObject);
}
if (deathBehavior == Death.InactiveUponDeath)
{
gameObject.SetActive(false);
}
}```
what happens if you play it outside of the coroutine
if you're destroying the gameobject here that has the audio source then you're interupting it too
how and where are you starting the coroutine?
The gameObject with the audio source attached remains active, but the gameObject nested under it gets destroyed
private void HandleVanishing()
{
StartCoroutine(DestructionCoroutine());
// Handle the boulder when its lifespan expires
// For example, you might want to deactivate it, destroy it, etc.
// Reusing the fallingTooFarBehavior for simplicity, or you can define a new behavior
}
where does that run?
is this happening each frame for example?
this added no new information
also this isn't DeathCoroutine
it's different - DestructionCoroutine
Oh wait I gave the wrong code by accident
I have the following in my awake method:
audioSource.clip = rollingSound;
And my destructionCourotine is not working:
private IEnumerator DestructionCoroutine()
{
collider.enabled = false; // So the player's bullets no longer collide with the enemy.
boulderMesh.SetActive(false);
destructionParticles.Play();
audioSource.Stop(); // Stop any currently playing sounds.
audioSource.clip = null;
audioSource.PlayOneShot(destructionAudioClip); // Play the destruction sound.
// Wait for the longer of the two durations: the specified destruction duration or the audio clip's length.
//float waitTime = Mathf.Max(destructionDuration, destructionAudioClip.length);
//yield return new WaitForSeconds(waitTime);
yield return new WaitForSeconds(destructionDuration);
// Proceed to deactivate or destroy the GameObject after the wait.
if (destructionBehavior == DestructionBehavior.InactiveUponDestruction)
{
gameObject.SetActive(false);
}
else if (destructionBehavior == DestructionBehavior.DestroyUponDestruction)
{
Destroy(gameObject);
}
}
ok so again
Where is this running?
Is it happening every frame?
This courotine isn't called every frame. Its called once the gameObject's lifespan has expired
private void Update()
{
Debug.Log("Boulder Position: " + this.gameObject.transform.position);
// Decrement the lifespan each frame, based on the time passed
lifeSpan -= Time.deltaTime;
// Check if the lifespan has expired
if (lifeSpan <= 0)
{
HandleVanishing();
return; // Skip further processing in this frame
}
// Continue with your existing movement logic
Vector3 movement = Vector3.right * moveSpeed * Time.deltaTime;
transform.Translate(movement);
if (transform.position.y < minYThreshold)
{
HandleVanishing();
}
}
private void HandleVanishing()
{
StartCoroutine(DestructionCoroutine());
// Handle the boulder when its lifespan expires
// For example, you might want to deactivate it, destroy it, etc.
// Reusing the fallingTooFarBehavior for simplicity, or you can define a new behavior
}
right so
unlike what you said
this IS running every frame
I think it has something to do with the rollingSound and destruction sound mixing together
so that's why the sound is playing weirdly
because every frame you're stopping and restarting the sound
Update runs every frame, and you're calling this in Update
I thought the code only played it if the condition if (transform.position.y < minYThreshold) is met?
ok thanks so much for the help!
I'm working on making a struct that holds a Class Type, and an Enum that determines which menus are compatible with one another, derived from an Abstract Class.
Assuming I have the Abstract Class "BaseMenuController", and the derived classes "PauseMenuController" and "InventoryMenuController", how can I define a variable that can contain either PauseMenuController or InventoryMenuController?
I basically want to set it up so I can give each menu type a list of compatabilities with each other menu type, so you can't open the inventory while paused, pausing closes the inventory, ect, ect, by defining how which classes interact with which other classes.
I'm uncertain which type of variable would be best for this.
Assuming I have the Abstract Class "BaseMenuController", and the derived classes "PauseMenuController" and "InventoryMenuController", how can I define a variable that can contain either PauseMenuController or InventoryMenuController?
BaseMenuController menuController;
Thank you very much, that works great!
It's just a sample script, but ScriptableObjects are basically just data instance which you primarily read from. Create a profile instance from the asset menu and create a variable of type EntitySO on your enemies and insert that profile reference onto them. Now, your enemies have some default data they can be instantiated with.
Hey gang, let me know if this is the wrong channel for this --
I'm currently experiencing a strange issue with sprites in my build appearing like so.
So far I haven't been able to find a common thread between the sprites. None of these issues are happening in the editor.
Any suggestions as to where to start looking to solve this?
Thanks for any help! (Tagging @indigo summit )
This art style rules. It looks like some sort of sprite atlas corruption. Sprite atlases can be set to build at various different points, I would have a play around with Project Settings > Editor > Sprite Atlas > Mode, if it's just set to be enabled for builds, test it as enabled in the editor too and see if that causes it to occur then
If it's only happening on one computer, I would say to upgrade your drivers
Also note that this is a programming channel, and unless there's code that could be related, it's probably better suited to #🖼️┃2d-tools or #💻┃unity-talk
Aha good to know. Tried it on my computer and my collaborator's, same issue.
The player character's movement Atlas seems to be the one thing working so it must be an issue with corrupted Atlases.
(Thanks for the compliment on the drawings!!)
why is Random.Range inclusive for float max but exclusive for int max?
Because it makes it easy to use with collections
thank
So you can write myArray[Random.Range(0, myArray.Length)] without a -1
ok, thank
What does this mean?
inclusive means include, exclusive means exclude. The max value you give it will be included (aka can be chosen) for floats but excluded (not chosen) for ints.
Ah ok, and same for minimum?
no the minimum is just included
Oh, no matter what?
yes, itd be kinda tedious if it wasnt like this
I guess
I was just asking since i hit an issue like this before, and i was very confused why the random.range excluded my value
these are the code related to movment and unit selection
[11:29 PM]
everything works fine, however i have an object i created called ground market, it simply is supposed to be a quad as a placeholder at the moment and does nothing but appears where you click once the unit starts moving there. if you have ever played an RTS game when you select a unit and right click to move that unit to a place there is a market or an arrow or somthing on the ground letting you know where you clicked and mine is not appearing
[11:29 PM]
also if i can do anything or you have any tips to make my code more readable please let me know i always want to improve on readability
sorry i dont kno0w if this is a beginner question or a general one
i am not really a beginner with coding, just game engins and how they work
(Thanks for the suggestion, it did up being an atlas issue and things displayed normally when I went through and set up manually made atlases for every sprite)
Annoying you had to do that!
I have a list of structs, which I'm wanting to use a foreach on, but it's not letting me, I think due to the fact that the function is being called in a different object?
//Contains the list of interactions between this menu and other menu types
[System.Serializable]
public struct MenuCompatabilies
{
public MType Type;
public BaseMenuController menuController;
}
So I have a list of these on an object
I pass that object to a function in a master object, for processing, I try to use
foreach(MenuCompatabilities menu in Origin)
But it doesn't recognize the MenuCompatabilities struct in the second class. Do I need a copy of the struct in both objects?
Here's the class with the Struct in it
https://pastebin.com/sUsBiyT4
and here's the function that's being called, (Called "ChangeMenuStates")
https://pastebin.com/XrtijbuK
I've removed the guts of the foreach loop in it, because it's not recognizing the struct when I type it.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I basically just want to loop through a list of structs, and check against their contents
but in function held in a class other than the one the struct is defined in
Me?
maybe
if you have a list containing a struct, can you just foreach the things inside the struct directly?
I assumed you had to foreach the struct itself, but I might be wrong.
I'm not getting an error, it's just not recognizing the name in editor, when I try to type it into it.
So
foreach(MenuCompatabilies menu in originCompatList)
Doesn't work, because it's not recognizing the MenuCompatabilities struct in a function inside a different class being run by the object in question, and I'm not sure what the solution is.
well, if you can show me where in the code that is cause I dont see it
Line 80
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
- Yes, you can for each a list of structs.
- If it doesn't recognize the type, then it's not accessible from that place.
It's a public struct in the other class, though, do I need to have duplicates of the struct in question? Or put it in something like a public static so it is recognized globally?
what does the error say
Error CS0246 The type or namespace name 'MenuCompatabilies' could not be found (are you missing a using directive or an assembly reference?)
it's not able to access the Struct, but I don't know what the step to resolve that cleanly is.
No you don't. Do you understand what's the actual type signature of the struct, considering it's nested in a class?
type signature? I don't understand.
//Contains the list of interactions between this menu and other menu types
[System.Serializable]
public struct MenuCompatabilies
{
public MType Type;
public BaseMenuController menuController;
}
This is the struct in question, and it's nested in a public abstract class?
You also have MState and MType in a similar situation. How do you access these types from outside the class?
I don't understand what you mean, I'm really sorry.
Yes. So how would you access the type from outside the class?
Okay, let's start simpler. Do you know namespaces?
may need to do BaseMenuController.MenuCompatabilies, otherwise take it out of the class the struct
it doesnt look like it's in a namespace
Mao, don't spoil.
lol whoops
Thank you, I think that's the solution I needed.
I was literally just asking because I didn't know what specific solution I needed to access it, since I had never run into this issue before.
and it's kind of an obtuse problem to google.
Yeah, now I understand the concept more fully. I just needed to know what I had done wrong.
Again, thank you very much. That solved the problem.
Would I need to create a new health class specific to the GameObject if I want to utilize ScriptableObjects?
A little more context please.
I have a health script that I use for multiple game objects, and I want to make a scriptable object for one of those game objects without affecting the others
What's the purpose of the SO?
Holding health and XP values, both are different scripts
So there's Health.cs and XPOnDeath.cs
Is it like a constant value or would it be changing?
Constant
Okay, then why would you need several SOs?
I guess to define different values, but then I don't get the question
Wdym by "create a new specific health class"?
For more context, I have a game object that gives the player XP when it's destroyed. There are three XP givers prefabs, each one has more XP and more XP than the previous one. There's going to be 500 or so of those spawned on the map, and when you destroy a lot, the game's going to spawn more to keep up. Would I need scriptable objects to change their HP and XP values?
Afaik to make a scriptable object you need to specifically define it in your class, and that'd just add more and more fields in the inspector that other game objects won't use
If you want manually defined values for each one, you'd need to create that many SO instances.
Yes, to create an SO, you need to extend ScriptableObject class and define the desired fields.
So no solution to this
Oh well, I'll just deal with it. 500 objects isn't much in the grand scheme of things, especially since it's a 2d game
You'd usually have a formula that gives you higher values procedurally, instead defining the them manually for this kind of stuff.
Anyone has experience with lyra? Been on this for like 12 hours, Ue5 source build is compiled, The Lyra game game is compiled, 12 hours later and every fix from google it still wont allow me to build a dedicated server :S
Hello. Maybe anyone know how to load random pictures from the folder?
Resources.Load("LoadedPictures/picture"+Random.Range(1,6).ToString());
Oh. Thanks again :)
I made some kind of mobile rhythm game, according some of my testers when using bluetooth headphones the audio is very async.
For the main modes i have implemented a calibration system already which seems to work well.
But for some short modes i cant make use of the calibration as im playing many short audio clips at the time a entertrigger responds.
What could be my best option to fix this issue ?
Fundamentally there's no way to fix it, the delay when you reactively play a sound to that sound gets to the bluetooth headphones is a hardware one.
You can use some assets to lower the delay, but really there's no way but to tell players that it's the reality when using a high latency audio device.
How do this kind of assets are named which can lower the latency of audio devices ?
Here's one I use: https://exceed7.com/native-audio/
Do read how it works before making the purchase though, it might not be what you need.
yeah this does not seem to be the right for me unluckily (no support for "Pitch" & "Low latency wireless/Bluetooth headphones") but i gona look for similar ones
someone please show me how to share ur whole project with someone for free
Share as in "let them play" or share as is "they can open it in Unity on their side" ?
open and do whatever they want so they can code with me
i tried github but you need to buy more for bigger project
Make a Git repository, and share it to them
then you probably pushed too much, did you use the Unity .gitignore?
there you go then, delete your repository, use the correct .gitignore and then make a new repo
Alright
I have 3 prefabs - Coins, Cars, and Pickup Items. For all 3 of them I have a Separate Spawner script as all 3 have different spawn logic. Now When they spawn, sometimes these items spawn very close to each other or on top of each other. I want a functionality that checks if any item is very close to new spawn point selected, it skips that and spawns at next 'y' position ( Basically I am making an endless runner game, every item spawns at middle of roads, so I want a minimum y distance between all items)
Problem: Items spawned are sometimes on top of each other or very close to each other
Have some higher level spawn manager that governs the positions that the specific spawners are allowed to spawn at.
how do i do that
Depends heavily on what you have so far.
As I said, depends heavily on your project, but in general something like this for example:
public class SpawnManager
{
Spawner[] spawners;
public void OnSpawnSomething()
{
foreach(var spawner in spawners)
{
var spawnPos = GetSpawnPos();
if(IsValid(spawnPos)
{
spawner.Spawn(spawnPos);
}
}
}
}
can i make a script that enables/disables all the other 3 spawner scripts after every fraction of seconds? so that avoids colliding?
Sure, that's an option as well🤷♂️
I would say it makes more sense to simply generate a sensible pattern of items in a centralized place
rather than disambiguating three separate spawners.
You can code whatever you like as long as it doesn't break the laws of physics/logic
so i would have 3 coroutine functions running in one script.
no
probably a single one, or no coroutine
but it can choose from multiple items based on whatever criteria
i tried an approach of setting a random function choosing between [0,10], for some range of values it would select one coroutine, or vice versa. But that just crashed unity due to many items spawning suddenly
Is it possible to create an animation that follows the cursor? Like the one on this video https://www.youtube.com/watch?v=DPqc7qYDtzM but not just modifying the Z rotation but rather completely triggering a different animation when mouse points somewhere else? Like say a 2.5d game, project zomboid sort of mechanic but the sprite is 2d
In this video we will learn how to Aim a Melee Weapon at mouse pointer in Unity 2D. In the later video I will show you how to perform an attack and how to create enemies to fight with.
Make a Juicy 2d Shooter course:
https://courses.sunnyvalleystudio.com/p/make-a-juicy-2d-shooter-prototype-in-unity-2020
How to get input using the new input sys...
Simply trigger animations based on the mouse position relative to the animated object position.
"Divide" your screen into 4 segments - up, down, left, right (or 8 is you have diagonal animations) and check in which segment is your mouse
i got isshues whit the genaration of the world bc my world should generate infinite but it dont generate at all could you please help me? this is the code for the generation: using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LevelGenerator : MonoBehaviour
{
private const float PLAYER_DISTANCE_SPAWN_LEVEL_PART = 200f;
[SerializeField] private Transform levelPart_Start;
[SerializeField] private List<Transform> levelPartList;
[SerializeField] private Player player;
private Vector3 lastEndPosition;
private void Awake()
{
lastEndPosition = levelPart_Start.Find("EndPosition").position;
int startingSpawnLevelParts = 5;
for (int i = 0; i < startingSpawnLevelParts; i++)
{
SpawnLevelPart();
}
}
private void Update()
{
if (Vector3.Distance(player.GetPosition(), lastEndPosition) < PLAYER_DISTANCE_SPAWN_LEVEL_PART)
{
// Spawn another level part
SpawnLevelPart();
}
}
private void SpawnLevelPart()
{
Transform chosenLevelPart = levelPartList[Random.Range(0, levelPartList.Count)];
Transform lastLevelPartTransform = SpawnLevelPart(chosenLevelPart, lastEndPosition);
lastEndPosition = lastLevelPartTransform.Find("EndPosition").position;
}
private Transform SpawnLevelPart(Transform levelPart, Vector3 spawnPosition)
{
Transform levelPartTransform = Instantiate(levelPart, spawnPosition, Quaternion.identity);
return levelPartTransform;
}
}
so ill set the mouse position as a parameter right?
on the animator menu
I always set up such things in code rather than the animator, so no clue
got it. can i atleast @ you later on once I get all my sprites drawn to help with the code?
Hey im using a Horizontal Layout Group. Is it possible that it spawns next row and not on the right ?
enum Direction { Up, Down, Left, Right }
Direction GetDirection(Vector2 obj, Vector2 target)
{
Vector2 relative = target - obj;
float x = relative.x;
float y = relative.y;
if (y >= 0) {
if (y >= Mathf.Abs(x)) {
return Direction.Up;
}
} else {
if (y <= -Mathf.Abs(x)) {
return Direction.Down;
}
}
return x >= 0 ? Direction.Right : Direction.Left;
}
```I believe something like that will be enough if I didn't make any mistake
It's gonna be 2.5d i'm using a 2d sprite on a 3d platform so I have to use vector3 right?
I'm not sure if that even matters
Got it. Thanks for the help, I'll have to take a look at your code and see what it all does as I'm still learning c#
You can just ignore the height of where the object/player is placed, since you can just assume that the object/player is on the same level as the mouse
You only need the x/y direction (or rather x/z, since y is the height)
Oooh okay thank you 😁
It's basically math
f(x) = x & g(x) = -x
And I assume the "enum" indicates the animation/sprite names to be used when that if condition is met?
enum Direction is just a type to make it more readable as to which animation should be used
You can either make a switch(direction), go through each possibility and play the correct animation
or as I like to do it, make an array of string-to-hash for your animator and choose a hash based on the enum (cast to int to get the index)
Yeah that makes more sense. Basically assigning an ID to each direction of the sprite anim
I'll plot out all the sprites first. Thank you for the help, I'm just thinking ahead as I realized that I need this code for the 2.5d aspect to work
private static readonly int[] s_animations = {
Animator.StringToHash(...);
...
};
[SerializeField] private Animator m_animator;
private void Animate(Direction direction) {
int index = (int)direction;
int animation = s_animations[index];
m_animator.Play(animation);
}```Something along those lines
** **
if anyone having issues with idiot players on windows putting game into folders ending with whitespace characters and game failing to load because of a bug in mono System.IO.Path.CanonicalizePath(string):string I made this workaround:
private static readonly char[] DirSeparators = { Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar };
public static string FixPath(string path)
{
if (string.IsNullOrEmpty(path)) return path;
int sepIndex = path.IndexOfAny(DirSeparators);
if (sepIndex == 0)
sepIndex = path.IndexOfAny(DirSeparators, 1);
StringBuilder pathBuilder = null;
int startIndex = 0;
for(;;)
{
if (sepIndex < 0)
sepIndex = path.Length;
if (char.IsWhiteSpace(path[sepIndex - 1]))
{
if (pathBuilder == null)
pathBuilder = new StringBuilder(path.Length + 4);
pathBuilder.Append(path, startIndex, sepIndex - startIndex);
pathBuilder.Append('.');
startIndex = sepIndex;
}
if (sepIndex == path.Length)
break;
sepIndex = path.IndexOfAny(DirSeparators, sepIndex + 1);
}
if (pathBuilder == null)
return path;
pathBuilder.Append(path, startIndex, sepIndex - startIndex);
return pathBuilder.ToString();
}
just use it on Application.dataPath / Application.streamingAssetsPath, it works because adding . to the end of file or folder name doesn't change it on windows, it's still same name, but it tricks CanonicalizePath function into not trimming valid whitespace characters, so instead windows API itself would do the job correctly
how come not using persistentDataPath?
persistentDataPath will rarely have whitespace characters at the end of the path, only if player has it in their user name
but dataPath and streamingAssetPath can have such folders in path because player can put game in a folder with such name
and it's been my constant headache
What are you using those paths for where it causes a failure?
opening files?
What code did you write that failed to open a file?
anything that uses System.IO.FileInfo / System.IO.DirectoryInfo / System.IO.File / System.IO.Path
so any attempt to open files with .net api in such folder fails
because it incorrectly canonicalizes name and removes valid whitespace character from path
how did you construct the path that you passed into it?
Path.Combine(Application.streamingAssetsPath, fileName)
you can easily reproduce it, just create folder with name (EN SPACE, not U+0020 which is actually invalid on windows and you won't even be able to create such folder) and put game in it, then try File.Exists on any path inside it or log Path.GetFullPath on any path
such path breaks most unity games
unless they do not use any dynamic loading at all and everything is statically loaded
so it breaks if they puta folder with whitespace?
not whitespace, specifically whitespace at the end of name, and not U+0020 whitespace (it's invalid on windows and windows wouldn't even let you create folder with such name) but any other unicode character in whitespace category
that happens because mono's mscorlib for some reason canonicalizes name on its own instead of relying on windows to do that like core clr does and it does it incorrectly - it calls TrimEnd() on every path part instead of TrimEnd(' ', '.') (skipping parts with names "." and "..")
code I gave adds . at the end of such names, which tricks function to not trim anything at the end and then when path is passed to windows api it canonicalizes name on its own correctly trimming . at the end without trimming whitespace character
other option is to patch mscorlib bundled with unity
Does anyone know how to unlock achievements easily on their Steam game? I can't succeed no matter how hard I try
if (SteamManager.Initialized)
SteamUserStats.SetAchievement("your achievement");
this sounds insane if so, can imagine there's a ton of published games that completely break with this if so, no chance does everyone properly handle this edge case
yeah, it's just not a common issue because most people don't use such folder names but when they do this is extremely hard to figure out
Hello, I'm currently trying to create a procedurally generated dungeon and I'm running into the issue of overlapping rooms. I have created an unconventional method for linking rooms and I'm wondering if anyone has suggestions as to how to proceed with my current progress.
right now I have two prefabs for rooms, each with their respective exit and entry doors, each exit door will then create an instance of a new room, connecting to the entry door of the instantiated room and it will repeat for as many rooms as we'd like to generate, but, as I've said, they are overlapping, any idea on how to deal with this?
are the room convex and/or concave?
well, regardless I would think the easies solution would be to check the AABB of the new room against every other room that's already been placed. if there is an overlap then try to place another room of a different size or mark this as a dead end. and yes you can probably optimize this using an quadtree, but that's a future problem.
Not sure if there's a dedicated channel but does Unity Ci support 2023 or not yet?
whats Unity Ci ?
sounds like continuous integration
wouldn't that just be the unity cloud build system?
Game Ci docker package, no clue where to even ask about this, I don't think its directly supported by Unity
I'm not asking for somebody to write this just a point in the right direction
I was wondering how I can push a sphere out of any intersecting objects?
I was thinking of Spherecast but it needs a direction and 0 max distance doesn't work
I was thinking of OverlapSphere which.. technically works? I just don't know how costly ClosestPoint is
Are there any other solutions that would be more efficient? After all the end goal is to push an object out of another it doesn't need to be perfect
Looks like their suported Unity editor versions are here https://game.ci/docs/docker/versions
Docker images versions
Spherecast generally would've been perfect if it weren't for that fact. It provides a normal and everything
there's a method for this!
The physics engine does depenetration automatically itself, no? But there's https://docs.unity3d.com/ScriptReference/Physics.ComputePenetration.html for that reason
- gah too slow
Lol no worries thanks guys too dense to find that
you give it the position and rotation of both colliders explicitly
But yeah it's on an object that cant really have a rigidbody
see the example:
bool overlapped = Physics.ComputePenetration(
thisCollider, transform.position, transform.rotation,
collider, otherPosition, otherRotation,
out direction, out distance
);
I remember suggesting to someone that they just write a wrapper for it
it'd be something like
That's not too costly right? It seems like it's taking a lot more into considering in comparison to a collider and a position
public bool ComputePenetration(Collider first, Collider second, out Vector3 direction, out float distance) {
return Physics.ComputePenetration(first, first.transform.position, first.transform.rotation, second, second.transform.position, second.transform.rotation, out directino, out distance);
}
just to make the function calls less...awful to look at
The position and rotation arguments are useful for asking if colliders would overlap
PhysX is pretty optimized
but that's not what you're doing here; you're asking if two colliders are already overlapping
Yup, you nailed it. I'm on 2023.3 and of course that's too new, thanks Praetor
The primitive colliders each have a Vector3 center property for offsets, which gets ignored here. It's not part of Collider though 
The center is part of the shape of the collider.
It will be factored in.
I was worried about that at first too (:
Oh, cool
Hi, im trying to make a game where you can spam 2 buttons to activate the same function, but currently having both pressed inputs set to the same functions makes it so that the 2nd button can't be pushed unless the 1st one is unpressed. imagine cookie clicker but you can spam 2 buttons basically (for example), how would i do this in the new input system ?
Wait sorry I think I might've communicated something wrong here. I know if 2 colliders are overlapping I just want to know how to push them out of eachother
Yes. This tells you how to push them apart
see the out params
You could either setup both buttons in your input action asset, or you can use Keyboard.current, and check (I think its) .wasPressedThisFrame property, and call your function in 2 separate if-statements, though in general it seems odd to me that you might need 2 buttons to call the same function at the same time, unless your maybe setting up a "primary, secondary" type of interaction, though even in that instance youd probably only want the function to be active from either rather than both id imagine
i want to make it easier to call the function in quick succession, since spamming 1 button is alot harder and annoying than spamming 2
and isn't keyboard.current the older input system that isn't compatible with the new one? i put both buttons in the same function and it makes me unpress the 1st button for the 2nd one to work
No Keyboard.current is part of the new system
Yeah ComputerPenetration is literally spot on thanks you guys
The old system is exclusively the things in the Input class
Slight issue a lot of things are going to be using mesh colliders and for whatever reason ComputePenetration thinks it's okay to go through those
I can make workarounds but the ground isn't flat at all so it's only temporary
does this mean i have to set each button as an individual action instead of putting both buttons under one action?
you can do what you want with a Pass-Through action
i.e instead of action having button 1 and button 2 would i need actiobutton1 and actionbutton2
i tried that but releasing the button also causes it to be activated
which isn't what i want
you need a little logic my friend
you can't just blindly trigger your thing
check the value
and do the thing for every time you see a 1
how do i check the value ?
depends on which workflow you're using
This question is basically "how do I use the input system"
how do i use that specific part of the input system yes
i know how to call a function from an action but not check the value of an action every frame
Again it depends on which workflow you're using
i mean i've got this bro idk
get rid of the 'else'?
this is a weird amalgamation of multiple workflows
IDK why you'd do it this way
Are you trying to read two different actions here?
Because that can work but yeah get rid of the else
cus i was using something else then someone told me to use that instead
to do what i want
Looks like you're using the generated C# class (asifde from the Keyboard thing, which you should remove)
in this case, make your action a passthrough and subscribe to the .performedevent on the action
then in the callback function you read the value from the CallbackContext parameter
how do i get the value?
i have no idea what a buffer is
you're tunnel visioning
I simply linked you to the list of methods on the class
you don't have to use the one you don't understand
ReadValue<float> or ReadValueAsButton
aight got it thx
do you have steamworks.net installed in your project?
yes but it didn't work
do you have the steam manager component in your scene?
Also, if you are subscribing with .performed you should also make sure your unsubscribing from it at some point, such as in OnDisable or OnDestroy
just .Disable()?
Youd want to unsubscribe (-=) your function from the action you subscribed to (+=), so for example:
void OnEnable()
{
input.SomeMap.SomeAction.performed += SomeFunc;
}
void OnDisable()
{
input.SomeMap.SomeAction.performed -= SomeFunc;
}
Where SomeFunc is your function using the CallbackContext param
doing input.Disable(); will disable all of the actions inside. No need to manually disable certain actions
but no disable doesn't unsub
if (Input.GetMouseButtonDown(0))
{
_initialMouseOffset = Vector3.zero;//restes the _initialMouseOffset vector
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); //gets the mouse position
NodeClass nodeToMove = (CheckIfPosIsOnNode(mousePosition)); //returns the node that is on that position
_initialMouseOffset = mousePosition - nodeToMove.transform.position;
}
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
foreach (var selectedNode in _selectedNode)
{
// moves the selected nodes relative to the _initialMouseOffset
Vector3 newPosition = mousePosition - _initialMouseOffset;
selectedNode.transform.position = new Vector3(newPosition.x, newPosition.y, selectedNode.transform.position.z);
}
i want to move the selectedNodes relative to the mous position. But currtently i am just setting the position of every node to the mouse position - the offset. And I don´t know how to go from there
If you're moving a group of nodes, wouldn't each one need to know its offset from the mouse position?
would make sens
I would say... calculate the mouse offset each frame and add that offset to each object's position
(world space offset)
e.g.
Vector3 previousMousePos;
void Update() {
Vector3 currentMousePos = // calculate current mouse world position
Vector3 mouseDiff = currentMousePos - previousMousePos;
foreach (var thing in thingsToMove) {
thing.transform.position += mouseDiff;
}
previousMousePos = currentMousePos
}```
of course also set previousMousePos to current position whenever you need to start the drag thing
and add logic for whatever clicking/holding of buttons you need
Thx
Im trying to insert an item into a list at position 13 and for some reson it says the position is out of range but its only 13, why does it break ?
presumably that's a list you're inserting items into
yes
if the list doesn't have that many elements, you can't insert an element at that position
perhaps you want a dictionary here?
oh, i thought it would resize automatically, thats what i found on the internet
it will as you add items
hey how to use OnCollisionEnter/Exit?
My Questions:
- Should the item that has the script attched have a rigidbody or the other one that is collided with?
but it won't add a bunch of default items to fill in the space when you try to use Insert with an index that's too large
go through these pages
Ok
Hey but anyone that doesn't answer with a link
how to use OnCollisionEnter/Exit?
My Questions:
- Should the item that has the script attched have a rigidbody or the other one that is collided with?
thank you
Read the pages I linked you to. They will answer your question (and other questions you didn't know you had).
they are concise and thorough
The script can go on either object with an involved Rigidbody OR either object with an involved Collider
Collision messages aren't sent to the object with the collider if a parent has a rigidbody (unlike with Trigger messages), which is a little tricky.
So if i make a dictionar like this with the int being the "index" and the vector being the value i need how would i get the vecotr from index x ?
Dictionary<int, Vector2> frontiers = new Dictionary<int, Vector2>();
as for the necessity of a rigidbody at all, see https://unity.huh.how/physics-messages/collision-matrix-3d
index the dictionary with the integer
frontiers[3]
you will get an exception if no such item exists
Hey my problem is that how to have a collider and RigidBody and a Charachtre controller at the same time i wanna do that HOW ?
thank you so much
You wouldn't do that
unless maybe if the RB is kinematic
Oh ok but will it turn off gravity and Collision Detection?
the kinematic rigidbody is not affected by physics
If you're using a CharacterController you need to implement your own gravity
unless you use SimpleMove, but that's very limiting
How?
why do you need a rigidbody and a collider on the same object as your character controller?
keep track of current velocity in a variable, add to it each FixedUpdate, like how gravity actually works
note that the CC itself functions as a collider
if you hit the player with a projectile that has a rigidbody and a collider on it, you'll get a physics message
Ok i have done it before and thats why i'm asking so here's my code :
{
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
float jumpInput = Input.GetAxis("Jump");
// Check if the player is grounded
// Movement
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
// Apply gravity
if (isGrounded && velocity.y < 0)
{
velocity.y = 0f;
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
// Jumping
if (isGrounded && jumpInput > 0)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
}
void OnCollisionEnter(Collision C)
{
if (C.gameObject.tag == "Ground")
{
isGrounded = true;
}
}
void OnCollisionExit(Collision collision)
{
if (C.gameObject.tag == "Ground")
isGrounded = false;
}```
looks like you already have gravity implemented here
you need a different grounded check though
i know but i will record a video and send it to you
use a raycast or something
yeah your grounded check is busted
I recommend following a tutorial
Why ?
because that only works for Rigidbody motion
you're using a CharacterController
switch to a raycast-based grounded check
What you have is not really a good grounded check for Rigidbodies either anyway
Ok then but i don't realy understand it so i will do some reseach
Your character controller will not produce OnCollisionEnter/Exit messages when you hit the ground
the controller calculates how to move without getting stuck in a wall
so it never actually causes a collision; it just moves to the right spot directly
Ok
Can you explain How to Do a raycast grounded check ?
- Note : "If u want to Help to do it"
- "If not IDC"
I'm not forcing anyone here
The best way would be for you to look at examples
Ok
but essentially you do a raycast from your character downwards. If the cast hits the ground, you're grounded
otherwise not
@heady iris , I cant use dictionaries since i sometimes get entries that should have hte same cost but i cant add 1 to every key so i would need to create a new dict every time a key already exists just to push back every other value by one
what are you actually trying to do?
it looks like some kind of optimization algorithm
But it tried bool isGrounded = controller.isGrounded
👆👆👆👆
no, this stinks, use a raycast
especially since your code has sort of a CC Move bug in it
but that can be fixed later
isGrounded tells you if you tried to move downwards into a collider the last time you called controller.Move
You call controller.Move several times
the horizontal move will almost certainly make .isGrounded be false
since you will slide along the ground without trying to move down into it
I know that but my problem is that how to check .isGroundedOnwhat(GameObject)
hi everyone, i have a question. in this image you can see i have multiple idle animations, my game has multiple different character stage sprites for each action, but i'd like to know the best way to go about this, i was attempting to treat the "Idle" state as an if statement to check if these 2 parameters are false, so it could trigger the actual animations (image 1 is the transition to "Idle", image 2 is the transition to "Player_Idle"), but it gets stuck (image 3)
im trying to make a path finding algorithm for creating roads on procedural terrain, im using this article as a refrence and im currently at the part wher i need to save the cost so the pathfinding preferes the path with the littles elevation change kind of to mimic real roads and i just need to sort my frontiers based on their current path cost
ah, okay, I just implemented this recently
(i was initially trying to lessen the complexity by not having the same condition in 5 different animation transitions)
You need a priority queue
In A* you iterate in such an order that you never have to recalculate the cost to get to a node. Unless of course your heuristic function is wrong
then all bets are off
C# has one, but it's not available in the version of .NET that Unity uses right now
Fortunately, priority queues are dead simple
👆
im never recalculating the cost
So why would you need to "add one to each node" or whatever you mentioned
👆
yeah you need a prioerity queue for sure like Fen said
You don't need to spam - again, use a raycast to check if you're grounded
thats what im trying to do
oh wait, I'm not actually using this right now lol
how to prevent fixedJoint2D from stretching?
I should probably fix that..that's going to make my A* way slower
that whole thing is just for the priority que ?
i could just save it in a vector 3 and use the 3rd value for the cost
then i can go back to my simple happy list
It's an implementation of a priority queue. A priority queue is a data structure that you can dequeue the lowest (or highest) scored element from efficiently
you notice curves, I want to fixed in a gridlock kind of way
I only put fixedjoint2D
So you throw a bunch of values in, then ask for the one with the lowest score.
It's not a sorted list.
that looks really organized but i dont have this much time since its for a game jam
the alternative is to just iterate over the entire list every time
which is...what my A* is doing right now, lol
All you need is the ability to find the smallest element.
alternatively, just grab an A* library and get on with your game
Made my sorting algorithm, id need an open source one and id need to understand how to make it find the best path across a texture basically. that sounds more complicated to me. mine can already go from a to b and avoid slopes higher than 45°
int GetLowestCost(List<Vector3> l)
{
float HighestCost = 0;
int index = 0;
for(int i = 0; i < l.Count; i++)
{
if (l[i].z <= HighestCost)
{
index = i;
HighestCost = l[i].z;
}
}
return index;
}
A* is a very, very generic algorithm. All it needs is a list of places it hasn't been yet, the cost to go to a place, and an estimate of how far that place is from the goal
I implemented it as part of goal-oriented action planning for my game AI. I pathfind between world-states!
I want to pull the lever <- I pull the lever, so I need to be close to the lever <- I walk to the lever
goap is so cool
thats really cool, i wanted to add that but it seemeed too complex for me so i went with a simple state machine
oh yeah, it was a lot
and it took several tries before i really "got" it
it's also inappropriate for a lot of situations
yeah, it feels really neat now that I have it working
Is there a straight forward way to count a collider being disabled as a trigger exit for whoever was inside it?
hello can someone help me i'm trying to deserialize my json but it doesn't seem to work https://paste.ofcode.org/38vURTRZ6pjbDeA3zwtuPD6 , here's the json : https://gdl.space/hexulezodu.json
i'm going to smash it together with my objectives system and see if I can make NPCs automatically complete the same objectives the player is given
where do you define CharacterData?
what do you mean
The first image is the script I created to display a string when the player wins the round, and the second image is what displays when the script is ran.
show me its definition.
just like you showed us the definition of CharacterDataArray
you need a newline
"\n" is a string containing a newline character
