#š»ācode-beginner
1 messages Ā· Page 91 of 1
how do i make it so that when i rotate the player it's always facing forward on the x-axis
i have to make it a child object of something right?
mouse movement
so how do you want to rotate him and keep him facing fowrad on the x axis on the same time š¤
do you have head as a separate object?
just so that i move forward in the direction their looking
you just said you want to rotate
yeah the whole body is in parts like a normal model
This is what I do usually
public class Player : Monobehaviour {
private InputManager _inputs = InputManager.Instance;
[Header("Rotation Values")]
[SerializeField] private float sensX = 20f;
private Vector2 rotation = Vector2.zero;
private void Awake() {
if (_inputs == null) _inputs = InputManager.Instance;
}
private void Update() {
// Basically just get the rotation.x value from your horizontal mouse movement,
// Idk what way you do it yourself, but it should be pretty easy.
rotation.x += _inputs.GetLookInput().x * Time.deltaTime * sensX;
Quaternion yaw = Quaternion.AngleAxis(rotation.x, Vector3.up);
transform.localRotation = yaw;
}
}
Not 100% sure its gonna work the way you want it to work, idk how your project and other code is set up
but it'll rotate the player character left or right
i think my code and everything is all good i just need to make it rotate locally
fps controller?
yeah
oh
how do i check if i get inputs from a controller or from keyboard&mouse
just shot you a dm
InputSystem.current
on new input system
InputDevice inputDevice = InputSystem.devices[0];
if (inputDevice is Keyboard || inputDevice is Mouse)
{
Debug.Log("keyboard/mouse");
}
else if (inputDevice is Gamepad)
{
Debug.Log("controller");
}
because that is not valid C# syntax
how would i do it correctly?
what are you trying to say with that line?
if i get an input corresponding to Fire2, it should fo these lines
so why (0) ?
oop, i originally had it at "Input.GetMouseButtonDown(0) and simply forgot
You even underlined the line! How did it not ring any bells??š
but even without the 0 it doesnt work
true because GetAxisRaw does not return a bool
Does it throw an error? Read it.
the error is "method name expected
what? show code
so? if GetAxisRaw is what?
what does getaxis raw actually give me? is it a range from 0 to 1?
read the docs
The compiler is confused. It doesn't understand what you are trying to do.
neither does the programmer apparently
thats why im in the beginner channel. i dont even understand how to read the unity scripting docs because the entire page is built like a hierachy
can someone help me I keep getting this error when ever I try and cloud save, it keeps saying there is something wrong with my script and i only have 2 scripts but they are both correct and I'm so confused someone please help.
the only thing to understand is
so i have to do GetAxisRaw("name") >= 1) to get it to trigger every time a button under that axis is pressed
yep, works
would be simplier to just use the new input system
Yeah tbh
Its so much better than the old one
Does need a bit of tutorials to understand it, but code monkey and samyam did some unbelievably high quality work explaining it amd showing it off
hello, I am trying to compare the position of a object at frame-1 and current frame to know if the object is moving or not. Problem is that I have an error telling me the vector2 position variable (for frame-1 position) isn't declared and it doesn't work if I declare it in public class block....
Also its a bit funny how they didnt fix a typo for years now, making it so the search box doesnt work for listening for inputs
But the 1.8.0 pre-release packages do work now lol
You'd have to show the code and any errors you received. What you're describing is very straightforward
You have to declare the variable outside the method
that's what I have...
as you can see I try to declare Vector2 lastPosition right in the public class but it doesn't work
I get an error in currentPosition != lastPosition
anyone know for this
as a sidenote, your speed should probably be declared as:
[field: SerializeField] public float speed {get; private set;} = 3f;
It doesn't look like you're using the "lastPosition" field at all.
You are redeclaring the variable on line 63. Don't do that
Maybe share the whole code.
serialize field makes it appear in inspector. public lets other classes see it. private set stops other classes from modifying your speed. =3f makes the default value in inspector 3 (or whatever) when you make a new component
right what the correct syntaxe to assign it to the position then ?
lastPostion = ā¦.
Just get rid of Vector2 at the beginning of line 63
You don't need to repeat the type every time you assign the variable
Vector2 lastPosition declares a whole new variable, also named lastPosition
That creates a new variable
and no, the IDE will see that and just let you do that
because it assumes you know what youāre doing
because you can totally declare something like:
public MyClass(float variable) {
this.variable = variable;
}
So you can make methods where the argument has the same name as one of your class fields
btw another other common option to declare a variable is:
[SerializeField] private float speed;
This makes speed only accessible within this class, but makes it appear in inspector (and saves the value)
problem is that it gives me an error
Why'd you get rid of new
that doesnāt make sense
I only told you to remove the beginning of the line
Leave the rest alone
BTW you can just do lastPosition = transform.position;
you are trying to assign lastPosition to be a new instance of a Vector2, created with its constructor
You don't need to be crafting the thing from scratch in the first place
I only want 2d vector so idk if that would work
It works
Try it
It converts automatically
Vector3 and Vector2 can be cast into each other
this is an implicit cast. Since lastPosition is a Vector2, and you are trying to assign a Vector3, the program searches for an implicit cast of vector3 to Vector2
other classes require explicit cast. Which requires something like: lastPosition = (Vector2) transform.position;
(if that were an explicit cast)
private PlayerControls playerControls;
private void Awake()
{
playerControls = new PlayerControls();
}
private void Start()
{
playerControls.Inventory.Keyboard.performed += ctx =>ToggleAactiveSlot((int)ctx.ReadValue<float>());
}
private void OnEnable()
{
playerControls.Enable();
}
private void ToggleAactiveSlot (int numValue)
{
Debug.Log(numValue);
}
so i set up my 1-4 keys on keyboard via the input system and tried to print them with numValue howhever it would always print me "1" no matter if i press 1,2,3,4 on the keyboard...
someone mention i can use callbackContext.control.name which returns the name of the key that was pressed , any idea how to implement that in script ?
ReadValue<float> is only going to return 0 or 1 for keyboard keys
You've assigned alt keys basically, not other values
You should just make 4 separate actions and assign each to an individual key
no way of bypass it by using callbackContext.control.name? and then int.Prase to convert string to index ?
Why would you want to overcomplicate it this much?
What happens if the user rebinds the key? It's much more robust to make 4 actions
It will take you 2 minutes
this smells fishy
it's a little hard to express. you're relying on information that just happens to exist for the keys you're using (the name you get back from control.name)
if you want four input actions, define four input actions
it's like if I decided how much health an enemy gets based on what color its material has
Sounds exactly like a lot of code we see around here š
Anything to avoid actually explicitly spelling out intentions
I have a a BuyItem script that sends a request to a database to remove the gold and add the item
If I do _ = BuyItem() it works perfectly in the client but it bugs in my database
if I do await BuyItem() it lags on the client and looks & feels really slow/weird
The database sometimes lags a second or two - causes items to duplicate, or multiple buys where you don't have enough gold but the gold is not substracted from database yet when you click a second time, ...
Is there any easy way to fix this? I want it to be smooth client side but work properly on the server side
there should be 4 separate input actions defined for each key
your code should depend on the inputaction that is invoked. Not on the specific key pressed. that is kind of the point of inputsystsem
hello, when I want to build my game, it shows me an error message. Can you help me please
because if you put this into PS5, and you are checking for pressing the 1 key, a PS5 controller doesnāt have a 1 key
so basicly u want me to seperate each key to an invidual action?
yes
Yes. If they're completely generic actions, then just call them "Action 1", "Action 2", etc.
if you later decide you want to use QWER instead of 1234, you can now easily change the input bindings
InputActionAsset lets you bind different keys to one action. So you can make a āJumpā input action. This input action is triggered by: spacebar on keyboard, gamepad button 4, PS5 controller X button, Nintendo Switch joycon A buttonā¦.
and if you decide you want to use an xbox controller, you can just add a binding for controllers
then you donāt need to code anhthing different
One of the main goals of the input system is to separate bindings from actions
this is for an infinite runner game
because your code just reads/subscribes to āJumpā and not the specific gamepad button
This is one case where the benefits are less obvious
basiclly the keys are for inventory scroll and which number the player press the same inventory slot index gets highlighted, is it really the best way ?
I also have at least one project where I've got something like
"Action 1", "Action 2", "Action 3", ...
i would not call them like that, but that is the idea
like āInventorySelect1ā, āInventorySelect2ā
where each one is literally just any ability the player might have
hence the vagueness
InputSystem listens for any keys that trigger InventorySelect1. Your code listens to InventorySelect1.
thats right
I can see why this would feel bad to implement
code no longer needs to know if you are on keyboard or xbox or a toaster
we'd all be annoyed if we saw this:
public float value1;
public float value2;
public float value3;
just do a List<float> !
tbf, you are assigning separate buttons on a keyboard/controller
I think the tricky thing here is that this feels like numeric input
so how the hell do you know which button on a joycon is 1 vs 3? lol
e.g. letting the user type "32" or "13"
but it's not. you just happen to have nine actions corresponding to the 1-9 digits.
If the user was just typing in a number, you'd absolutely not make ten input actions for each digit
you'd just read keyboard input
yes
agreed
i still have an issue with input system for several months that I never figured out
very much it does , your help is much appriciated , ty ā¤ļø
I remember the painful days before I knew about lists, I'd add like 40 lines for 40 different objects to disable on function š„²
itās an error called ācontroller binding not foundā, or something. I think the cause comes from trying to bind/unbind a virtual mouse, but itās hard to diagnose because the error message is not useful
this is why I advocate for basic programming classes lol
the biggest mistake novice programmers make is honestly bad style
bad style?
let me see if I can pull up an example
this is what bad style looks like:
var r = ((int)o << rb[(int)b])
+ ((int)o >> (4 - rb[(int)b]));
r = r & 0b_1111;
if (b >= 4) {
r = (r & 0b_0101) + (r << 2 & 0b_1000) + (r >> 2 & 0b_0010);
}
return (Cardinal) r;
}```
the code is written in a way where you cannot tell wtf it does
good lord
in grad school, I once got a program to run a complex specialized instrument
the program was about 2000 lines long. super technical. variable names a, b, c⦠j, x , y z t w
one comment with a citation to a paper
i had to tell my PI āthis isnāt happenning, chief. Weād need to start from scratch.ā
point being, style isnāt something you learn from bro code or braexys. You learn that in school lol
I mean I don't use correct snakecasing or anything like that, but my code is still readable š
instructors will not put up with bad style. you will straight up fail your class if you have bad style
I actually got marked down in VB lessons for optimizing the code too
very sad moment
hello, when I want to build my game it gives me an error message
Post the message
Ok
the only two things i understand it &0b1111 and if(b>=4){}, i guess it is trying to swap the Left/right up/down
Ok
same code but in proper style:
public static Cardinal RotateCardinal(Cardinal original, Rotation rotateBy) {
Debug.Assert((int)original >= 0, "Tried to rotate a NEGATIVE cardinal value! Cardinals should be 0-15!");
Debug.Assert((int)original < 16,"Tried to rotate a cardinal that was >15! 15 is the max for having the total # of directions!");
// Bitshift to represent rotation. Moves all 4 cardinals into right spot in flags
int rotated = ((int)original << rotationBit[(int)rotateBy])
+ ((int)original >> (4 - rotationBit[(int)rotateBy]));
// Now the main 4 bits are right. Get rid of out-of-range bits.
rotated = rotated & 0b_1111;
// More bitmath. That operation above rotates by 2, so L/R are flipped. now isolate U/D and add back in
if (rotateBy >= Rotation.sigma) { // Need to do a mirror plane
rotated = (rotated & 0b_0101) + (rotated << 2 & 0b_1000) + (rotated >> 2 & 0b_0010);
}
return (Cardinal) rotated;
}```
š 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.
also #854851968446365696
this should give Tina some closure
you cannot make build with Editor namespaces
either delete it if you are not using that namespace
or add preprocessor directives
#if UNITY_EDITOR
btw, the code I posted was just for demo purposes. To show good vs bad style. not because i needed help with it.
did you end up making/using scene gizmos icons, or just ones for your scripts?
so I am still trying to check if an object is moving by comparing its position at frame and frame-1, here is my code but it still doesn't work because "currentPosition" always has the same value of "lastPosition"
i downloaded some icons and put them on some key monobehaviours that appear frequently. it made it a lot easier to navigate gameobjects with ~10 scripts
!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.
because you assing it to the same value
in the same frame
is there a way to save the position at frame-1 then ? I tried using the methode LateUpdate but didn't seem to work that well
oh, definitely. i started making my own gizmos to select empty GameObjects from the scene. now i'm hooked on making icons for specific scripts, like controllers, managers, databases, etc. i'm afraid every script will have their own custom icon, lol . . .
what do you need it for
I need an ennemy to change direction when it's stoped by a wall (like a goomba in mario)
I am doing a 2D game with 3D assets btw
firsly, you dont need an extra variable for currentPosition
just use transform.position instead
then in the LateUpdate() i'd just do
void LateUpdate()
{
if (transform.position != lastPosition)
{
Debug.Log("Object is moving");
}
else
{
Debug.Log("Object is not moving");
}
lastPosition = transform.position;
}
if you are using the physics system, then you need to do this at the end of fixed update
he is not
iam using characterController
iām not familiar with how character controller plays in terms of physics
keep your Move() in update and in late update use the code i've pasted
if you need last frame position, then you need to save current position right after whatever mechanism actually changes it
is there a way to get like a log of what happened right before unity stopped responding and I had to manually close it through task manager?
unity should generate crash dump file on crashes
do you mean the console in unity editor?
on mac, it is the system console
does it still count as a crash if I had to manually close it through task manager? if yes where can I find those
let me guess, infinite loop? š
I'm using windows
stackoverflow exception?
honestly I don't know what's causing the crash but I'll report back when I find out š
90% of the cases are infinite loops freezing the entire editor and sometimes PC aswell lol
if you have a stack overflow, unity will instantly crash and close. If unity freezes, that might be an infinite loop, and idk if you can see that on an editor log
It probably didn't generate the crash dump if you shut it down.
freeze doesnt generate editor log
hmm, how could I find out what's wrong then
With a debugger
but when you say freeze, the whole thing stays open, but stops responding, right?
yep
Technically, your app is still running. It's just not doing anything productive.
ok, infinite loop i bet
I'll go through the code again maybe post it here if I can't find it myself
first thing to check are any while loops or recursive calls you added recently
then add an emergency escape loop count
The fastest way to debug would be to cause the freeze and break with a debugger during it.
int interations = 0;
if (iterations > 100000) {
Debug.LogError(āFatal error. infinite loop.ā);
break;
}
I was thinking about how I didn't add any new loops and how there are only like 3 loops in the entire game, I think I know what's causing it now lol I'll try to fix it 1 sec
both while loops AND recursive calls are common culprits.
but with infinite recursion, youād probably hit stack overflow
š 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.
yes. Activate Slot 1, Activate Slot 2, etc..
for (int i = 0; i < enemyPrefabs.Length; i++)
{
GameObject enemyPrefab = enemyPrefabs[i];
int count = enemyCounts[i];
for (int j = 0; j < count; j++)
{
Vector3 randomPosition;
RaycastHit2D hit;
do
{
randomPosition = GetRandomPositionFromCamera();
hit = Physics2D.Raycast(randomPosition, Vector2.zero, Mathf.Infinity, enemySpawnLayer);
} while (!hit.collider);
GameObject enemy = Instantiate(enemyPrefab, randomPosition, Quaternion.identity);
enemiesInLevel.Add(enemy);
Debug.Log("Spawned an enemy");
}
}
this loop specifically if anyone was wondering, I forgot to create an enemyspawnarea in the boss room.
that looks like a terrible architecture
well this is the beginner's chat after all I don't claim to be an expert
loop inside a loop inside another loop
you should avoid nested loops
loop in a loop
but double nested loops are damn.. š
you should especially avoid a nested while loop
nested for loops are ok, but you need to be in control because the amount of calls grows quadratically
wow, never seen those before . . .
this spesific loops gets called like twice in the whole game therefore I was not too worried
the real danger is that you write a while loop that terminates after a very random amount of time
i have several in my codep
or that never terminates!
yes, that is a major hazard
do
{
randomPosition = GetRandomPositionFromCamera();
hit = Physics2D.Raycast(randomPosition, Vector2.zero, Mathf.Infinity, enemySpawnLayer);
} while (!hit.collider);
gambling
There is nothing stopping this from running forever.
It's also hard to reason about how long it will run for.
if you are making an enemy spawner, If I was you I'd try to make it from scratch, avoiding nested loops
i do have nested for loops. Like, if I need to search a tilemap for all instances of tile t, then I need to go: for (x in range) for (y in range)
I wouldn't say that nested loops are a problem at all here
yea this is a SpawnEnemy method
you can have a five layer bean dip of for loops and it'll just be slow (assuming each loop runs many times)
sure for grids etc its good
it makes perfect sense to do a double for loop here
but i dont see a reason to make them for spawning enemies (as long as it is not grid-spawning system etc)
for each enemy spawner, do:
for each enemy to spawn, do:
find a spot
That's completely normal.
I think your problem is that "find a spot" can fail to terminate
Fun tip: try stack allocing stuff inside a loop.
Is photon the only best multiplayer networking system? Is it better than fishnet?
there is a lot of networking systems
so you're saying change this part to "for each enemy to spawn" instead of this "for (int j = 0; j < count; j++)"
no, I'm not saying to change anything about the for loops
I'm just describing what your algorithm is doing
Hey @rare basin in order to do a system that my gamemode can max handle 10 players do I need to to configure room manager script?? I'm using photon
well i think what happened last time is the find a spot did not terminate because there was no spot therefore unity froze
i don't know what is your room manager script and what is your concept and code architecture
Precisely. That'd mean the do..while never exits.
I would suggest having it give up after a certain number of tries
A typical room manager script
i also have another nested set of for loops to iterate over all my assets. I have Wheels with lists of Family, which have lists of ObjBase, which have lists of alternate ObjBase, and each ObjBase can have multiple tiles.
My TileDirectoryClass has a big loop that goes:
foreach (wheel)
foreach (family in wheel)
foreach (objBase in family)
AddBase(objBase);
foreach(altBase in objBase) AddBase(altBase);
AddBase(objBase) {
foreach (tile in objBase) {
add tile to directory
}
I'm pretty new how would i add that condition?
that doesn't tell much
that is 5 layers of nesting
you could use another for loop, really
!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.
i donāt need help. Iām just discussing in the nested loop discussion
Okk
bool spawned = false;
for (int try = 0; try < 10; ++try) {
// try to spawn
if (itWorked) {
spawned = true;
break;
}
}
extreme pseudocode action
Okay sire
okay i see what you mean, i'll give it a go
point being, my 5 layers of nested loops works fine because Iām in total control. I know exactly how many iterations the innermost nested part of the loop needs to run. I know itās finite, and small enough to finish everything in the blink of an eye
the layering of lists in lists in lists is just for organizational purposes
yes, n^5 is okay if n is small
or if most of the loops only run a small number of times
in this case, the nesting is irrelevant
itās not really n^5. Total iterations is locked. So the number of layers of nesting could be 1-100, and it doesnāt matter
that's what i said, yes :p
it's n^5 with a small value of n
or maybe O(abcde) with small values for a-e
itās actually O(totalTiles)
zeus's problem is not that the innermost loop is being hit too many times
yes
it's that the innermost loop runs forever
yes, and totalTiles is a function of the number of wheels, families, objBases, and altBases
po-tay-to po-tah-to
my point is that you should analyze this exactly like you would any other algorithm
I mean I have a fixed number of tiles. then i put them into wheels/family/objBase etc to organize them. So exactly how i choose to split them up is irrelevant
it's not "different" because the numbers are fixed
because the loop is built backwards, in a sense
ah, yes, I see what you're saying
you know it's fine because you know how many tiles you have
you don't have to think about all of the other factors
that's fair
exactly
and I know that whole thing runs once at the very start of the game. so performance cost is de minimus
is this correct place to ask for guide with 0 hours in coding? š
it's the correct place to ask a specific question about a specific thing you're having trouble with.
you want some amount of experience first, or you wonāt understand our help
you can be learning, but it doesnāt help if you have never coded at all
because then weād be doing it for you entirely, and thatās not how we roll
I understand. Is the unity tutorial content good or would you recommend me something else to start with?
it's good enough
it works, thank you very much !!
like learning to speak spanish before becoming a telemarketer in Spain
sure sure
most intro programming courses teach python, because it is very beginner friendly
good starting point
thanks man I will ask you guys when I meet my first wall
is there a transform method to rotate an object by 180° ? (like just make it look backwards)
transform.Rotate might work
depends on what do you want to achieve
instant rotation or smooth etc
Does anyone have a good recomendation on making an inventory system that is kinda like minecrafts?
usually I multiply the quaternion by the relevant quaternion
transform.rotation = Quaternion.Rotate(ā¦.) * transform.rotation;
something like that
might want the other way around
actually, does that matter here? i remain fuzzy on this
i expect quaternion multiplication to not be commutative
rotation operators are not hard to deal with as long as you donāt need to get into the weeds, and remember they arenāt commutative
yeah, I just want to have a better intuition for what happens if I, say, switch them around
imagine a cat. head to tail is X axis. top to bottom is Y axis. left to right is Z axis.
Rotate by 90 degrees, X then Y. vs Y then X
thatās how my physical chemistry professor explained it to me
and the difference is the commutator
the commutator for that is Z rotation
at least that is what i remember
i played around with it am still quite confused
what about it?
i should point out that this is the old input system you're using here
whilst this code is for the new input system
If you're using the old system (i.e. you aren't using the Input System package), you'll need to do something different
i switched to the new one
okay, so what is the problem?
right now, i get what is plugged in, but i want to get the last input. because even if i input with my controller, it still debugs the keyboard
ah, I imagine that devices is just a list of all available devices
hi my visual studio code does not have the list of unity functions after i do rb.
have you followed the steps in !ide ?
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
⢠Visual Studio (Installed via Unity Hub)
⢠Visual Studio (Installed manually)
⢠VS Code
⢠JetBrains Rider
⢠Other/None
nope -- maybe you're thinking of stuff like Mouse.current
hmm maybe š
I use control schemes in one of my games to decide which input hints to display
yes
void OnInputUserChange(InputUser user, InputUserChange change, InputDevice device)
{
if (user.id == playerInput.user.id && change == InputUserChange.ControlSchemeChanged)
{
SetControl();
}
}
this is from a class that displays an input icon
here, have the entire class https://gdl.space/hucavigovi.cs
hey, I can get rid of that TODO!
you can ignore most of the SetControl method.
I use InputBinding.MaskByGroup to filter bindings by control scheme
tyvm
since I'm using control schemes
It sounds like you just need to know what kind of device is being used, so most of this is irrelevant, actually, lol
you really just need this
Although I am a little unsure what device will be here!
since I'll have both mouse and keyboard devices in use
thx
show me screenshots of:
- the External Tools settings
- the package manager "In Project" list
Do you need to know whether a keyboard or gamepad caused an action to run?
Or do you need to know when the user switches from keyboard to gamepad input?
il get the other one sec
i need to know when the user switches. i have a mechanic that works slightly different for controller users so i need to switch if needed
I would suggest creating control schemes and assigning your actions to them
Then you can just check user.controlScheme.Value.name to see which scheme they're using
(using a method like this)
@swift crag is it this?
Yes, and that looks good
Visual Studio Editor is up to date
Close VSCode, then double click a script asset to reopen it
im getting this, does this mean anything
didnt fix
ngl im probs gonna just delete and use microsofts version of visual studio instead
its fine
Does anyone have a good recomendation on making an inventory system that is kinda like minecrafts?
that was gonna be my next question!
There is an extension called ".NET Install Tool" that's supposed to automatically download the software you need
For some people, it doesn't work. Mysterious.
You should be able to just hit "Get the SDK" and install .NET yourself
yeah i installed it, probs not in the right place though because it didnt work
you'll need to restart VSCode at the least, and probably your computer too
to make a type of 2D controller for a character similar to the game Hollow Knight, how should I do it professionally,Give me concrete advice, what should I use?
tbh, I'd say to just try it. Do it several ways -- both kinematic and non kinematic rigidbodies
Make small games (maybe look for game jams to do) with very different platforming mechanics
just download the sdk manually
you want to make your game feel as fair as possible, so learn about things like "coyote time" (letting the player jump for a brief moment after going off a ledge)
This is the extension that downloads the SDK, not the SDK
oh
did you click "Get the SDK"
show me what you installed
ah, yes, I should have specified
ok 1 sec
installed this
restarted everything
still wont autocomplete any unity code
@swift crag thanks for ur help but i am just getting the purple version instead
i give up
did you regen project files after you did this?
give that a whack, yeah
woo
been stuck on this for like days, been youtubing and googling and you guys solve it super fast
thank u!
Hey guys, is there a way to stop the checkmark from disappearing whenever the toggle "Is On" property is false? Would like to instead change it to a different image.
wdym
I've done that step so many times at this point š
even though I still use VS
Change the Toggle Transition from None to sprite swap
Only gives me two options, fade or none
Usually when i have a no unity code problem in vs, if i go to Asset>Open C# project, instead of clicking on scripts or right click open, it works fine
Glad you got it working tho
Remove Checkmark as the graphic for toggle transition
Instead scroll up to "Transition" and use sprite swap there
Hey can you see why percHit may be 0? I have the Code and what the Debug line gave me. Both Input numbers are in int and the output is specifically declared a float but its just returning 0 instead of 0,75.
int division
(float) amount / (float) MAX_HEALTH
ohh thank you
3 / 2 = 1
because it rounds, alright
integer division is defined that way, to always output an int
1.5 is not an int, so no matter how it does it, you will never get 1.5
is there a similarly easy to miss reason why my slider always has double the value it was supposed to get? it was supposed to get its current value - 0,75 but instead it got its current vallue -1,5 which means it ended up being -0,5 and not 0,25
so most int division gives the same result as rounding down
image set to fill* not slider
Don't really get how I can swap the sprite with that whenever the "Is On" value changes
You can play around with the checkmark and background sprites. Checkmark is active when it is "On" and the background is visibile when it is not.
@eager elm The checkmark is always active, whenever the "Is On" is set to false it just changes the graphic alpha to 0
Hello i have these 2 scripts, and currently im only able to move the gameobject which i put into my inspector. I need to achieve a functionality where when a gameobject is clicked i can move the object clicked, and not the one in the inspector. By adding a static variable or other stuff, i just destroy the already achieved functionality. Im not good enough to add this on my own.
https://paste.mod.gg/ahrkeqofsuet/0
https://paste.mod.gg/qupcikcckvtp/0
A tool for sharing your source code with the world!
A tool for sharing your source code with the world!
You need to put code inside your function
Semicolon means "end of line"
So there's nothing in your SpawnPipe function
it terminates the statement, yes
It's exactly the same kind of error as this:
if (false);
Debug.Log("I shouldn't run!");
this is equivalent to...
if (false)
{
}
Debug.Log("I shouldn't run!");
there is you can see the instantiate below
in this case, it's not a compile error, but you will get a warning.
There is no code in your SpawnPipe method.
That's not in the function
You ended the definition with that semicolon.
okay so first trouble
I get an error when I edit my script in visual studio and it does not find same commands as the tutorial video does
The error code is CS1002 ;expected
Is the line underlined in red
so i am trying to make a button have a listner but am adding it via code. does anyone know how to add the object to it?
No its not
Then you need to configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
⢠Visual Studio (Installed via Unity Hub)
⢠Visual Studio (Installed manually)
⢠VS Code
⢠JetBrains Rider
⢠Other/None
so i am trying to make a button have a listner but am adding it via code. does anyone know how to add the object to it?
Ty bro!
i don't think that works with the way I am using it
AddListener(SpawnInventoryItem)
it caused this error what you suggested
just do it manually in your code with an OnValueChanged listener tbh
so its find the Visual Studio Code and it opens the script in the VS but it does not autocomplete the code
Then you've missed steps
Show the full line of code as you have it
that means you are missing a ; on like 18
If it's not underlined in your IDE, you need to configure it. !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
⢠Visual Studio (Installed via Unity Hub)
⢠Visual Studio (Installed manually)
⢠VS Code
⢠JetBrains Rider
⢠Other/None
hey since I cant find a clear answer online, is there a simple way to get the length of an animation clip using its name?
I bet using animation events would be better
Can you show SpawnInventoryItem?
Yeah that's probably the best way to do it
yeah, so difficult to find https://docs.unity3d.com/ScriptReference/AnimationClip-length.html
zamn
That function has a parameter, so it does not fit the built in delegate. Even optional, it still has one. You should make an overload that has no parameters, and one with a defined item
ok
thats still not finding it by name though, i know that it has the property length but i dont know how to find the animation clip itself.
An AnimationClip is an asset so use Resources.Load just like any other asset
So I did that and it is not adding the listener, should I be able to see it when I hit play
It will not show up in the inspector
Use logs to check if it's running
It is not working
Show the SpawnInventoryItem function with no parameters
So, you aren't getting the "CLICK" message when you click on it?
Try putting in another function manually in the inspector and see if that one logs, to see if your button is working at all
how do I create a quaternion that is looking in the forward direction of an object, and another quaternion looking in the backward direction of that same object ?
Does someone know a good tutorial for a state machine
It does not seem to be working, I also added another button but that did not work either
in me not really understanding and being confused, i watched through some yt videos and came up with this, however its not really working. even if i dont use the gamepad, i can only get a "controller" debug message. https://hastebin.com/share/galequpalo.csharp what did i do wrong or not understand?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Is your button responding to the mouse at all? Is it highlighting when you hover it, animating when clicking, and so on?
Quaternion.LookRotation is the method you want.
alright so I need 2 vector3 for this right ?
transform.forward and -transform.forward
since there's no transform.back
you should also pass transform.up as the second argument
Quaternion.LookRotation(transform.forward, transform.up) for example
The second argument determines which direction is "up" for the resulting rotation
Forward is just:
transform.rotation
this will be the same as Quaternion.LookRotation(transform.forward, transform.up)
this one is for the axis which the rotation is relative to ?
I would not say that.
In order to define an orientation from a "forward" direction, you'd need to also know which direction should be up, since it can rotate about that axis and still be facing the same way
You need two directions to define an orientation
if you do Quaternion.LookRotation(Vector3.forward, Vector3.right), the resulting rotation will:
- point in the forwards direction
- be rolled 90 degrees to the right
ok makes more sens ^^
I just have a syntaxe error preventing me from doing the thing tho :/
Hey Fen, sorry for the delay ,but is that what u guys were meaning ? i did create a seperate action for each number key , however i had to do 5 lines of code to initialize those lol , the code works though but it seems clunky, any advice please ?
look Rotate() docs
Rotate is a function
you cant use it as a variable
public class ActiveInventory : MonoBehaviour
{
private int activeSlotIndexNum= 0;
private PlayerControls playerControls;
private void Awake()
{
playerControls = new PlayerControls();
}
private void Start()
{
playerControls.Inventory.Keyboard1.performed += ctx => ToggleActiveHighlight(0);
playerControls.Inventory.Keyboard2.performed += ctx => ToggleActiveHighlight(1);
playerControls.Inventory.Keyboard3.performed += ctx => ToggleActiveHighlight(2);
playerControls.Inventory.Keyboard4.performed += ctx => ToggleActiveHighlight(3);
playerControls.Inventory.Keyboard5.performed += ctx => ToggleActiveHighlight(4);
}
private void OnEnable()
{
playerControls.Enable();
}
private void ToggleActiveHighlight(int indexNum)
{
activeSlotIndexNum = indexNum;
foreach (Transform inventorySlot in this.transform)
{
inventorySlot.GetChild(0).gameObject.SetActive(false);
}
this.transform.GetChild(indexNum).GetChild(0).gameObject.SetActive(true);
}
}
you can't assign anything to a function, it doesnt make sense
rotation, not Rotate.
It's not really avoidable, yeah. You can't neatly say "every number key is an input action"
I guess you could make a List<InputActionReference>.
and then iterate over it
yea list did come to my mind but i have no idea how to import each input and their index
InputActionReference lets you reference a specific input action
š ā¤ļø
I'm using this Script to controll a third player character, the character is supposed to turn into the camera's direction on a movement input while the camera is able to look around freely. Unfortunately it's not working as intended, even tho I followed a tutorial on it and double checked the script multiple times, any help appreciated.
using System.Collections.Generic;
using UnityEngine;
public class third_player_movement : MonoBehaviour
{
public CharacterController controller;
public float speed = 6F;
float turnSmoothVelocity;
float turnSmoothTime = 0.1f;
public Transform camera;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
if(direction.magnitude >= 0.1f)
{
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + camera.eulerAngles.y;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
transform.rotation = Quaternion.Euler(0f, angle, 0f);
Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
controller.Move(moveDir.normalized * speed * Time.deltaTime);
}
}
}```
it didnt change rotation
on input
but i found the issue
i forgot to
refrence what transform to rotate
lol
has to be "controller.transform.rotation" in the 7th to last line
Is there a clean way to serialize dictionaries in the inspector?
right now I'm using a custom class
Use a premade SerializableDictionary solution or just serialize a list of key/value entry structs and load them into the dict in Awake
this is what I usually do
yeah that's kind of what I'm doing now, creating a warpper SerializableDict class like so
[Serializable]
public class SerializableDictionary<TKey, TValue>
{
[SerializeField] private List<SerializableKeyValuePair<TKey, TValue>> _contents;
private Dictionary<TKey, TValue> _dictionary;
private Dictionary<TKey, TValue> Dictionary
{
get
{
_dictionary ??= InitializeDictionary();
return _dictionary;
}
}
public bool TryGetValue(TKey key, out TValue value)
{
return Dictionary.TryGetValue(key, out value);
}
private Dictionary<TKey, TValue> InitializeDictionary()
{
return _contents.ToDictionary(keyValuePair => keyValuePair.Key, keyValuePair => keyValuePair.Value);
}
}
especially if the data doesn't change at runtime
The problem with making a List<KeyValueStruct> and making a dict out of it in Awake is that the dict won't update if you mess with the list
it's also annoying if you need to access that data in editor scripts
i ran into that yesterday
There aren't really any other options for this that aren't just slight variations of this.
i decided to just keep the list and search it every time š«
fair enough
(the list has at most six things in it, so whatever)
was actually considering that as an alternative too haha
You can solve this with ISerializationCallbackReceiver if you really wish
i'm already dealing with enough eldritch information
i'm not kicking this anthill more than I have to :p
When resolving merge conflicts for things like File ids, is it better to go with the source code, base code, or destination code?
How do I type decimals in VS?
4.81f
[SerializeField] List<InputActionReference> inputActionReferences = new List<InputActionReference>();
private void Start()
{
for (int i = 0; i < inputActionReferences.Count; i++)
{
playerControls.Inventory.inputActionReferences[i].performed += ctx => ToggleActiveHighlight(i);
}
}
``` getting "PlayerControls.InventoryActions' does not contain a definition for 'inputActionReferences" error , any idea why ?
you're trying to access playerControls.Inventory.inputActionReferences
you probably forgot to delete playerControls.Inventory off the front
also, you'll want to do inputActionReference[i].action.performed
InputActionReference lets you reference a specific input action. The outcome is the same as getting the InputAction from that playerControls object
i presume that's the generated C# class
I'm working on this game where I have NPC's that are powered by ChatGPT, and I want to have prompts in which I can parse bits of other prompts.
I feel like I'm switching data structures every day lmao
For now I settled on a solution where I can parse certain properties from scriptable objects into a prompt.
I'm going slightly insane though, asyou can misspell the token identifiers in the prompt and then stuff just breaks, so you have to be very precise.
No idea what a better solution for this would be haha
I mean it's not terrible but tomorrow I'll wake up and want to refactor it all again haha
You have the most versatile way to do it. Another simpler way of doing it is to use string.Format(), but you lose the explicit names as they're replaced with placeholder elements {0}, as well as accessing sub-properties with your dot operator a.b
yea it is , well , u solved the error but now the code dosnt work sadly , the methoed ToggleActiveHighlight dosnt get called and when i try to Debug .Log it says Value cannot be null
[SerializeField] List<InputActionReference> inputActionReferences = new List<InputActionReference>();
private void Start()
{
for (int i = 0; i < inputActionReferences.Count; i++)
{
inputActionReferences[i].action.performed += ctx => ToggleActiveHighlight(i);
}
}
private void OnEnable()
{
playerControls.Enable();
}
private void ToggleActiveHighlight(int indexNum)
{
activeSlotIndexNum = indexNum;
foreach (Transform inventorySlot in this.transform)
{
inventorySlot.GetChild(0).gameObject.SetActive(false);
}
this.transform.GetChild(indexNum).GetChild(0).gameObject.SetActive(true);
Debug.Log(indexNum);
}
and where is that error coming from?
see the stack trace
I'm suspicious of that ToggleActiveHighlight code

oh, this is just the inspector having a fit
it's trying to find a property that doesn't exist, for some reason
restarting the editor generally cleanses these demons
cleanses, exorcizes, whatever
lol ill try
I created an animation state in the Unity Editor but its missing in the Controller File, but why?
nothing fancy
Hit "Save Project" in the file menu
see if the file changes
ctrl-S saves the open scene. I'm a little unclear on what actually triggers non-scene assets to be saved.
I've never had a problem with them not saving...
the demon has been cleansed ! but now we need to deal with anotehr one becasue it dosnt print at all lol
nevermind works like a charm. saved the unity file. feeling stupid.
one thing to check: try doing inputActionReferences[i].action.Enable(); in the start method
This shouldn't be necessary
since you're already doing playerControls.Enable(), which will enable those input actinos
But I've never really used the generated C# class option
"transform child out of bounds" means you asked for a bogus child index
Hi, I have offered myself to a studio to program a inventory system for their game, but Im a bit nervous. So, could I show you the code structure (just name ans describe the classes and interfaces) Ive devised so that you can opine if its good? Or this channel is only for issues?
I know, "dont ask to ask", but Im not sure if I can ask that in this channel
You could ask it, but you'd probably need to give a ton of details for someone to be able to properly review it. Like how the inventory is used through other systems
Unity should show an asterisk at the top when changing something in animation controller.
Nope
Animator Controller is its own asset
Some assets do show that they're unsaved.
true yeah some custom SO do it
Well, the studio didn't tell me so much details about it... So for now I'm making it pretty simple. They just told me "you have to program an inventory", and after so much questions I found out that I have to do a basic toolbar. I think the items arent stackable.
the first step in writing a program is figuring out what you need it to do.
inventories are a common source of Design Problems (tm)
you need to ask more questions before you do any coding
they aren my that complex, but you really need to clearly define the constraints early on
thx for the correction
because changing the constraints later might require you to start from scratch
you often have several kinds of data mashed together into the inventory
weapons, items, key items...
some things can share behaviors and some can't
it gets gross
I know... I think the studio doesnt have a clear idea of how it really should work after all the questions I've asked. But I want to help them, even being aware of their poor organization
At least, for now I want to make a little prototype
Ask them more before you end up wasting time, like what the inventory does in the first place (not just hold items), what can it hold, can I drop items, can I swap items, can I use every single item that's in the inventory. Etc
are all items similar, or are there different kinds of items that need vastly different treatment?
Okay, thank you. Ill try to get all the answers I need (:
I ran into some problems making an inventory already and it's gotta somewhat be remade. It really is important to know what you want first. In mine, everything inventory related somehow became a dictionary holding different data
Try to make a list of questions before you contact them though so you arent going back and forth 20 times. Ideally they shouldve given you a list of functional requirements for it
Yeah, Ill make a list of questions, thanks (:
I have a special talent for ending up helping disaster studios
trying to wrap my head arount this , the logic seems right š
Maybe do some logging.
Are you off by one now?
Maybe you used to do 1-4 instead of 0-3
i is in a closure so it's always off by one. Should be
for (int i = 0; i < inputActionReferences.Count; i++)
{
int index = i;
inputActionReferences[i].action.performed += ctx => ToggleActiveHighlight(index);
}
i tried logging inside the for loop and it does print me 1 to 5
omg u solved it lol
Yeah that copy (int index = i;) is required when working with loops with lambdas that capture the loop variable in it. Otherwise at the time the lambda is executed, i will be always equal to .Count because the for loop has finished executing
@swift crag @keen dew ty so much!! ill restrain from spamming this channel for today at least xD u guys are amazing
yap! works like a charm
yeah. donāt lay down a single brick until you know if the house is even made of brick
I have the canvas shown below in my project. My goal is to be able to change the source image of "Image" to one of 7 possible images during runtime. Does anyone know how I could achieve this?
public Sprite[] myImages ;
var randomImage = myImages[Random.Range(0, myImages.Length)];
imageComp.sprite = randomImage;```
This^ but it's assuming you want a random one. The imageComp.sprite = someSprite; part is the most important bit. The rest depends on how you want to choose which one. to set it to
ah so you mean if it isn't a random image i just replace the randomImage line with how I select the image?
if you want a specific one just use the index of it
myImages[3] - this one gives 4th one for example
(assuming you want to keep them in a list of 7 sprites)
sure, however you want to select the thing
i've made the array for my images and added my elements. what is imageComp?
private void Update()
{
float translationfb = Input.GetAxis("Vertical") * thrust * Time.deltaTime;
float translationlr = Input.GetAxis("Horizontal") * thrust * Time.deltaTime;
ri.AddForce(transform.forward * translationfb, ForceMode.Force);
ri.AddForce(transform.right * translationlr, ForceMode.Force);
rotationX += Input.GetAxis("Mouse X") * sensitivity;
rotationY += Input.GetAxis("Mouse Y") * -1 * sensitivity;
cam.transform.rotation = Quaternion.Euler(Mathf.Clamp(rotationY, -80, 80), rotationX, 0); ;
transform.rotation = Quaternion.Euler(0, rotationX, 0);
}
this code is making the movement considerably more jittery than i expected. why is it doing this?
You are adding forces in Update, whch is a big nono
you are also rotating a Rigidbody via the Transform, which is another nono
The image component whose sprite you want to change
right, alright but what's the alternative to that
and how would i get that image component?
All physics belongs in FixedUpdate
make a reference to it
idk how i forgot that lmao
you can do the rotation here via rb.rotation if you wish, that part should be ok assuming it's simple y axis rotation on an upright capsule
The same way you get any other component
yeah its just a capsule
so i rotate rigidbody? not transform?
you'll also want to enable interpolation on the rigidbody
no
neither
neither rotation needs to go in fixedupdate
only the force
Also Time.deltaTime should not be multiplied into the force calculation either
because it doesn't make any sense
Time.fixedDeltaTime is already incorporated into the default ForceMode for AddForce
oh sick
and you'll be calling it in FixedUpdate, so everything will line up
rightttt
i forgot how helpful unity is lmao
movement still seems rather jittery tho
i might be going insane, but this definitely looks jittery
is there a way to get a list of PlayerInputs that have joined?
Id look at code in this example
https://github.com/UnityTechnologies/InputSystem_Warriors
Bad news today Glock US Legal department said I cannot use a glock gun in my game.
I spent all that time making the glocks and animating them, making sure they were commercial free from the Unity Asset store.
I tried to alter the glock, like remove bits from the main gun like the trigger and sight, to make it look different but they said it still looks too much like a glock.
Just letting you know this in case your using a copyrighted gun in your game.
But Dead Trigger 2 uses dual glocks, and so does the game Contract Wars, so I am not sure of the copyright permissions these games companies have or if they use the glocks illigally in their game.
Not sure why that has to do with coding?
But like anything that involves an IP you have to pay for a license.
Again, nothing to do with coding.
Show code
yup, those are 100% glocks btw
Okay so I cant get my Groundcheck Transform to appear under my scripting for the player. Any advice?
!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.
hi, just wnated to ask why im getting a nullreferenceException on my PlayerMovement ? thank you
You need to configure Visual Studio so it works with Unity
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
⢠Visual Studio (Installed via Unity Hub)
⢠Visual Studio (Installed manually)
new code
Line 57: you haven't finished typing the code for that function. This produces errors, so Unity can't update your code until they're all fixed.
ty
If that line is not underlined red, configure your code editor, this simplifies programming by a lot
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
⢠Visual Studio (Installed via Unity Hub)
⢠Visual Studio (Installed manually)
⢠VS Code
⢠JetBrains Rider
⢠Other/None
And that fixed it, tysm
why does my ui game object not apear in scene view
It's there, select it in the Hierarchy, move your mouse over to the Scene View and press F to focus it
thank u found it
In some computer games and RPGs, you get real guns with fake names. They have the appearance and the characteristics of the real gun, but not the name.
The reason appears to be avoiding potential lawsuits from the manufacturers of said firearms; it's a lot easier to prove a trademark infringement over a name than over the unique likeness of a weapon, and many companies haven't trademarked the latter anyway. There's also the issue of editorial control; much as car companies can dictate that vehicles in videogames not be shown crashing or being damaged as a requirement for licensing, gun companies could potentially demand their weapons only be shown in certain situations as a requirement for inclusion of their trademarks. Oddly, this often happens even with guns with which trademark issues wouldn't be relevant, whether because they're so old that trademarks have lapsed or because their developers went out of business.
In recent times, the likenesses of firearms have also been subject to this trope. The high level of graphical detail that modern computer games are capable of has caused some to fear that gun companies could take legal action on likenesses alone, regardless if a game uses fake names. Visual examples can range from minor embellishments to entirely fictional firearm models, the latter of which is typically done by merging visual elements from several real-life firearms into one designnote . In any case, the statistical behavior of these fictional guns are often closely modeled after real-life examples.
Show code
They can't let go over the fact that you indeed cannot use intellectual property and trademarks without permission
if(isGlock)
Lawsuit();
Context messages
- #š»ācode-beginner message
- #š»ācode-beginner message
Still not a code question though
yes ill not use glocks then
š¤
This is a code channel
Can you not continue the conversation here? Thanks
@short hazel sorry to be nuisance but could you breakdown what u were trying to tell me in #archived-code-general
if (enemy != null)
This checks that the enemy is not destroyed. It is essential, because without it, you get the error you're experiencing right now
bump
So in the braces { } right after that line, you're 100% sure the enemy is not destroyed, therefore you can use the enemy variable all you want there. After the braces, it might be destroyed, so you might get the error
I'm in my way to make a save system with JSON. I have an interface implemented in all the objects which I have to save or load data.
My problem is that I want to save or load the data from all objects who have implemented the interface, whether they are in the scene or not, I don't know how to do this. I don't know another approach besides searching the objects in the scene.
so after the enemy is destroyed is something still searching for the enemy but causing an error as the enemy isnt there anymore?
Does someone know a god free audioManager?
if an object isnt in the scene, how are you going to save anything related to it? What functionality do you hope happens
Yes, you access enemy.transform which is considered as a "search"
To be sure you won't get the errors, you need to move all the code that's after the yield and that uses the enemy variable, inside of the if statement
. How do I else save the data in other scenes? If I have 2 worlds and I save in the second one, how do I save the data from things in the first world?
Saving between scenes? What If I want my game to only have manual saving?
Well, if you buy into the whole omnipotence thing it'll be hard to find anything god-free
and a good one even paying a bit?
thank you so much, you explain stuff so well!!
I really dont know what you mean, are you talking about 2 scenes loaded additively? Easiest thing imo is having the objects to save register themself with a singleton save manager, instead of trying to find the objects.
If you're talking about 2 different scenes entirely, not additively loaded, then idk what to tell you. The objects arent there, so you wont be able to save an object that isnt there
i found a free one, but as far as i know it just let me to make more clear and ordered the project...
I've also thought about doing a persistent Save manager but I don't really know how to approach it. However thanks for secunding my thoughts hahaha, thanks!!
i have honestly not answered anything, I am asking you what functionality you are trying to achieve. What are you trying to save, what relation did your 2 worlds have that they needed to save things in each other?
I didn't want to be annoying with lots of questions
. What I meant with the worlds analogy is that I have let's say a town and a dungeon in different scenes. If I interact with an NPC in the town that leads to a change in the map and I later go to the dungeon and save the game there...
When I load the game again I want to load the changes made in the town scene too. I know I have to do a DontDestroy GameObject with an static class that holds...
Nevermind I just figured out while writing this what to do with the persistent class
I wasn't understanding but now I do 
me and GPT 3.5 what could go wrong
lol, nothing that ur aware of š
You want to use a serializable "progression" class that holds all of the game's progression data
when you quit the game, you serialize it to disk, and when you relaunch the game, you deserialize it
I'm figuring this out myself for a Soulslike game.
im using the player input manager, and when i load a scene the data doesnt get reset
where does the player input manager component exist?
its an empty in the scene
Is the object you have selected right now a child of the canvas?
no
UI text needs to be a child of a canvas.
(or a grandchild; it just has to have a canvas as one of its parents)
What is line 33?
Question: How do i make that work? The idea was a Platform, where the Players gets attached to, to move with it. After Exiting the Trigger unparents the Player. Problem: The Player changes its Size and stuff when i set the wordPositionStays to true, if false he teleports away.
One option: make the platform like this:
- Platform (not scaled, player is attached to this)
- Surface (scaled, has the renderer and collider)
You generally shouldn't parent things to non-uniformly-scaled transforms. It causes headaches.
Can i "apply" the scale?
like in blender for example
Sure. Apply transforms in Blender.
note that the platform may still be scaled (e.g. to [100, 100, 100]) by the import process
I would suggest doing this.
was working fine until i added a stystem that collecst coins that the nemy drops when it dies
"Surface" would be the model
well, now it's not working fine
so you'd better diagnose that
Doesn't change the fact that either enemy is null or it has no EnemyHealth component
The code does test enemy != null
thx ill look into it
how can i sort this out?
but ive added enemy != null?
Doesn't change the fact that either enemy is null or it has no EnemyHealth component
There's two things in that sentence
hey guys, my player movement is very basic. But I am afraid that when I am going in diagonal, i go faster than up, down, left and right. 2d game. here is the code: ```cs
private void PlayerMovement(){
float horizontalInput = Input.GetAxisRaw("Horizontal");
float verticalInput = Input.GetAxisRaw("Vertical");
transform.Translate(Vector3.right * playerSpeed * horizontalInput * Time.deltaTime);
transform.Translate(Vector3.up * playerSpeed * verticalInput * Time.deltaTime);
the word "or" is what is known as a "conjunction" to connect two independent clauses into a sentence
You need to normalize your direction prior to using it in your movement.
oh ok thank you! mankes sence
enemyhealth
If the code didn't exist then your code wouldn't even compile. That was never on the table
but the direction is the Input, and it doesnt accept the normalize
no clue what your saying
showing us this code told us nothing.
it doesn't matter what that script contains
GetComponent<EnemyHealth>() returns null if it can't find the component.
I'm saying either enemy is null or it has no EnemyHealth component
You'll need to construct a new vector2 which is both your horizontal and vertical input then normalize that vector.
Then you translate your position once using that vector (instead of twice like you're doing now)
but my enemys health script is called "EnemyHealth"
That script defines a kind of component
got it working š @swift crag
That doesn't mean the enemy has that component
or that whatever you hit here has that component
You should log enemy, as well as the result of enemy.GetComponent<EnemyHealth>()
what will that do?
logging enemy will show you what you're actually detecting with that physics query
No one is doubting that your script exists
and enemy.GetComponent<EnemyHealth>() will show you if the enemy has an EnemyHealth component
the enemy object doesn't have one on it
hmm ok got it, thank you!
yes. the script just defines what an EnemyHealth is. this doesn't mean that every object in the scene has an EnemyHealth
it's like if I told someone what a dog was, then expected them to automatically have a dog
how do i give the enemy th eobject?
The same way you add a component to anything
Either drag it onto it or hit the Add Component button
You might be hitting the wrong object here: an object that doesn't have an EnemyHealth component
We'll know for sure if you just log those two things.
this?
That is an EnemyHealth component, yes.
This object has an EnemyHealth component.
Since the enemy object does not have one on it, then this is not the enemy object
I'm not sure why you're spending your time doing anything other than this right now.
It will tell you exactly what is happening.
its attached to the enemy
but where here I add the vector? u mean I use only 1 cs transform.Translate(vector etc..etc..) ??? ```cs
private void PlayerMovement(){
float horizontalInput = Input.GetAxisRaw("Horizontal");
float verticalInput = Input.GetAxisRaw("Vertical");
Vector2 vector = new Vector2( horizontalInput, verticalInput).normalized;
transform.Translate(Vector3.right * playerSpeed * horizontalInput * Time.deltaTime);
transform.Translate(Vector3.up * playerSpeed * verticalInput * Time.deltaTime);```
I do not care. Log enemy and enemy.GetComponent<EnemyHealth>().
no clue what log is mate, unless you mean debug.log
Yes, Debug.Log.
Logging is often logging, yes
why are you multiplying by world right and up
you got a direction speed and delta time
no clue where the debug.log is supposed to go
I need help with this, I don't know how to make collision detection functions work. I don't even have anything showing up in the console (all I want to do is to detect if the player is in collision with a mob and teleport it to the beginning of the level). Both player and mob have a capsule collider btw
before you try to use the result of enemy.GetComponent<EnemyHealth>()
are those syntax errors on the method names? that seems odd
or is that another color
Warnings it seemy
Yeah probably
it says function is decalred but never used
If you declare a function inside of another function, it only exists inside of the containing function
Yeah, it's a local function, take it out of whatever it's in right now
You need to declare these things directly inside the class.
As the direction in your Translate function call as the first parameter
https://docs.unity3d.com/ScriptReference/Transform.Translate.html
Some time after the values exist, and some time before the error causes the program to stop
oh it's using translate call
think its time to give up on programming
log is not Log
Uppercase "L"
pay attention to spelling and capitalization.
What is a Debug.log
You will also need to debug the two things Fen told you, not some random string
is this correct?
No
Why are you logging random things instead of logging what you were asked and what would be useful to know
I'm confused here. Wouldn't it just be Translate(directionVector * speed * deltatime). Why are we using right and up here
also, I would suggest passing enemy as the second argument. this will let you click on the log entry to be taken to the thing you hit
Debug.Log(enemy, enemy);
like so
not sure, i though i needed it at the time but always worked fine
this will help if it turns out you're hitting something weird
That's legacy to what they were doing before. The next step is to replace that entirely with the newly constructed vector input.
mate ive got 0 brain cells and have no clue what im doing
it was in void update, I took out and it's inside the public class now but I still dont have anything in the console (no more syntaxe error tho)
if you aren't willing to put in any effort here, then we can't help you
If you aren't clear on something, ask
Then either stop and think or actually read what you've been told to do
don't just do random things and then throw it back at us
reminds me of some old snes games where running diagonal was busted too
failing to understand exactly what i need to do
What is unclear about this? #š»ācode-beginner message
then perhaps you need to take a step back and learn programming without the complicated 3D engine in the middle
will do eventually
idk how to log stuff is my point
Debug.Log(enemy);
you need to log the values of 'enemy' and the getcomponent..
Then you should not be doing anything else until you do
after you check if its there..
this will log the enemy variable.
Debug Log should literally have been the first line of code you ever wrote in unity
if you don't know how to do that, then you are way ahead of yourself
if enemy is !null -> debug.log(enemy) so u know what it is.
you can pass whatever you want to Debug.Log. It will get turned into a string and written to the console.
went straight in
if enemy is null then u find out why its null
These will detect collisions / triggers in a 3D project, so make sure you're using 3D rigidbodies and colliders.
Post screenshots of the Inspectors of the two objects that are supposed to be part of a collision here.
Yes, "going straight in" would involve you writing a Debug Log as probably the first line of code
but if it aint u'll know what it is.. by using enemy.name for example to log it's name or w/e
remember a variable is a container, you can log any variable to get its name, type, value, etc.. using Debug.Log()
inside the brackets.. with the rest of ur code
lol
and learn how to write anything
if you don't understand why this has completely changed the meaning of your script, then you need to sort that out first.
You should not be coding anything yet. You are still in the "learning what words mean" phase
we've spent about 15 minutes trying to get you to write two lines of code. you need more practice.
ah didn't know I needed a rigidbody as well, thanks
Congratulations, after trying literally every combination of letters and places to type them you have stumbled into the correct answer. Now go learn how to actually write code
https://learn.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/tutorials/
im guessing if it was outside it would be irrelevant as were trying to test when there is an enemy
ya, when the if(statement) is true
On at least one of the two objects yep
so its in the if statements { ... } body
should it be the mob or the player then ?
practice makes perfect
Monkeys on typewriters is not practice
is there anything else i should log?
you need to actually think things through and then execute on them, not just guess until people on discord tell you it's right
Depends on how you're moving your objects. For best collision accuracy you should be moving using a Rigidbody, so why not on both objects?
try and see.. see what it logs.. maybe log its name.. make sure its the thing u expect it to be.
sounds like you just want to measure the angle between the player and the enemy's forward direction
if it is, debug the getcomponent to see if that is what its supposed to be, etc
If it's below a limit, shoot a ray and see if it hits an obstacle
as of now I move both of them with a characterController because that's all I know yet ^^'
If you want that nice rectangular FOV, you'll want to test the horizontal and vertical angles separately.
you can use dot product
Oh, then you want to use the dedicated OnControllerColliderHit() function instead of OnCollisionEnter
@tender stagyou don't want to shoot out 10,000 raycasts
and check if anything is inside of that?
of the angle
I saw this function but apparently it doesn't work if the player isn't moving
Right, do note that a Character Controller emulates both a Rigidbody and a Collider (without being any of these at all!), so putting a Rigidbody and/or a Collider aside the Character Controller will make them conflict, you'll have weird movement issues as the physics system battles against the Character Controller
To do that, you can do something like this:
Vector3 toPlayer = player.transform.position - transform.position;
Vector3 eyeVec = transform.forward;
Vector3 verticalToPlayer = Vector3.ProjectOnPlane(toPlayer, transform.right);
Vector3 horizontalToPlayer = Vector3.ProjectOnPlane(toPlayer, transform.up);
float vertical = Vector3.Angle(eyeVec, verticalToPlayer);
float horizontal = Vector3.Angle(eyeVec, horizontalToPlayer);
ProjectOnPlane gets rid of the part of a vector that lines up with the second argument. So, the first one throws out the left-right part of the vector, and the second one throws out the up-down part of the vector.
(eyeVec should probably be the enemy's head transform)
You can think of ProjectOnPlane as "squishing" the vector into a plane whose normal is the second argument
so Vector3.ProjectOnPlane(transform.position, Vector3.up); gets rid of the Y component entirely, for example