#๐ปโcode-beginner
1 messages ยท Page 559 of 1

whats the exact reason of why binary files break themself when saved as string
AI = trash, apparently its replacing us programmers
That code had a comment every other line
ya, i just had to scroll up to see ๐
That's wild, looks like a dictionary
because you shouldn't be doing that, stop it
no like
binary containing strings
if i were to edit it in notepad it would break
but in hex editor it wont
why is that
Because binary isn't strings
but they in fact can hold invalid ones
so why not save it
actually it could be also beacuse of loading it
Binary is not a string. If it were encoded into a readable format, it would in fact no longer be binary, it would be a string
oh so i can for example read it as string and write it as bytes and it will still work?
he thinks its strimg because he opened it in notepad
Do you know what encoding is
it kinda would be easier if encoding was more universal
like it cant hold emoji and such
i dont know at which part encoding applies reading string dont need one but writing does
Encoding is what decides what the binary data means
encodes the binary akhem
At this point, just change your name to "StringObsessed", it seems that's all you seem to ask about in the weirdest use cases.
For real
stop trying to turn every piece of data in the universe into a string and back
and just learn proper serialization
Something something VRChat won't let me something something
i just wondered as i always had that issue of data disappearing when using notepad and how to avoid that
If you want to turn every piece of data into a single universal data type, guess what, there is one it's called byte and you that's what serialization is
also that, i wasnt even discussing save system on my map
and string is in fact still superior
in which world
You have no idea how long we've wondered that question
This is the same user who went on far too long about script length having a noticeable impact on their games performance. It's not worth getting into it.
there only bytes in memory, if you use strings to serialize (edit binary files?) the first is slow and require processing it in both ways
the 2nd in parentheses, well lets skip this part
the script length/amount of scripts cant affect game performance in the build, but in editor well, more assets to process, more data to hash, but its unavoidable, sounds like funny topic
It wasn't really, unfortunately
human readable serialization is highly superior ;)
makes fixing merge conflicts actually doable
i do enjoy being able to easily edit serialized data
it's much less efficient to use delimiters and to limit yourself to just printable characters
however, comma,
YALL MADE MY FIRT EVER GAME WITHOUT A TUTORIAL and a bit of dicord help
but still this is progrres
๐
hey guys! i need a pointer, i'm recreating the slenderman game and as most people know whenever he is close static appears on your screen, whats the best way to recreate that in unity? should i use transform.distance? or should i do it some other way?
i don't know (never played it), but if you're checking how close/far one object is to another, that's just a distance check . . .
so pretty much just make a variable that stores the player's transform then enemy.distance - player.distance?
what does player.distance or enemy.distance return?
oh! not distance, sorry, i forgot the term right now, but i think i'd be able to calculate their distance by subtracting both of their transforms, so like, player.transform - enemy.transform
i dont know exactly, i gotta write up the code, just looking for some pointers and to confirm if this is the best way to go about it
gotcha, was wondering if that was smth else. but yeah, it's just a distance check, so you're fine. you can search: "unity check distance," for a bunch of answers . . .
post processing volume
how come?
i recreated this effect before for my game and all i did was enable a gameobject thats already a child of the player so that i didnt have to manipulate any transform values
how? with post processing or...?
what does post processing have to do with anything i said
its simple..
because Spawn responded with, "post processing volume," and you chimed in right after (about creating an effect). it sounds like you're talking about the same thing. you never specified if you were talking about checking the distance or creating the effect . . .
i assumed it was the same way as the other guy said, my bad
the volume controls the fade/ the distance/ all that stuff
oh whoops sorry
thats if the noise profiles are good enuff for what u want to do
yeah what i was talking about was creating the effect; simply enable an inactive gameobj
thats the easiest method i can recommend
you may have to explain more. enable and disable a GameObject to do what?
the post process volume does it all itself? naturally?
i was about to ask, and how did you make the effect become stronger as the enemy got closer to your player model, Ash?
omg i just reread your message and i understood it completely wrong mb ๐ @compact stag
ur good!!
ignore me please
u set the volumes size, and then the blend distance and whenever the camera enters it'll add the effects
hey yall just wanted to know the difference between lists and arrays and when is best to use them
and how would i go about setting the transparency of the video? i want the video to be almost opaque next to the player and transparent when the enemy isnt around
heres a good discussion explaining this https://stackoverflow.com/questions/434761/array-versus-listt-when-to-use-which
thanks!
film grain -> set the settings u want.. (this will be max settings)
and then its all about ur fade..
once u've left the trigger its automatically transparent..
in -> full effect
out <- no effect
and any fidelity inbetween by changing the parameters
wait, so, film grain actually effects this? is this a specific use since its static or does that apply to everything else? (assuming film grain is the thing that makes it more/less transparent
because i was planning on using a static video and putting it over the screen
but using this idea might be better
film grain is the noisy stuff over the top... u can change its intensity
but its not really opaque or transparent
oh! right, just noticed i never mentioned using a video on top of the screen until now, apologies
gotcha! i appreciate your help
i'll take a look at it! thanks a ton
i like the italic in it
post processing is screen effects..
gives a bit of suspense
so it could be placed on top of a video..
yup! i just never thought of using it for some reason
jsut not UI.. (unless its worldspace or overlay UI)
so, question
if film grain adds static to the screen, can i change the static's pattern someway?
static is by definition random noise , so no
#๐ปโcode-beginner message this makes me think u can
(that's my best guess)
but again.. i dont know how to use it. so maybe search it up and see..
actually that depends
i know u can w/ shadergraph pretty easily
shadergraph? whats that?
what exactly do you want to do? do you wanna display an image on the static? do you wanna change the contrast?
that makes a lot of sense tbh
It's time for not just one shader, but 10! In this video, you'll learn about 10 different shader effects, what they are useful for, and how to make them in Shader Graph!
๐ Download the project on GitHub: https://github.com/daniel-ilett/10-shaders
๐ Huge thanks to my Patreon supporters for March 2022, especially: Jeremy Gooch, Morrie...
a tool to make shaders
well, that question i asked was just out of curiosity, but my goal is to make it so that when the enemy gets closer, more and more static will appear on your screen (i'm recreating slenderman
thank you!
array: set size (cannot be changed)
list: dynamic size (can change)
use arrays when you know the size or limit of the collection.
use lists when you don't know the size or limit of the collection, or if it can expand (increase) in size . . .
nice thanks!
Array: Menu Items
List: Customer Reservations
Hey, i need some help with with Vector 3 projection which doesn't seem to be working [
(here's the code before anything else)
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
So, the red sphere is representing a point on a plane
the green one is supposed to be the red point, projected onto the green line
however, as you can see, it's on the floor for some godforsaken reason
It looks like it's projecting at an offset
Does anyone know where to find resources on making a turn based game. I see some frameworks but I have no experience with turn based stuff. I was looking into a fire emblem style game
or more like Fell seal and FF tactics
oh right! sorry
NP
If someone could take a look at this, it'd be much appreciated
brackeys has a good tutorial on it. gamedev.tv and code monkey does as well.
Hello, I am going to start randomly generated rooms for my game soon (2d), and I was wondering how I am able to add terrain through my tilemap through code.
sorry if this is confusing through words (which is why i am having trouble search for an answer), but currently I have a grid object with a tilemap object inside. the tilemap object has terrain i built. how can i build terrain in the tilemap through code (which ill be using for random generation)
any help or links to related stuff is appreciated !
I don't know if anyone has any recommendations for how to troubleshoot this, but recently I came back to my project, and, I'm not sure if this was there before, but I'm only just noticing now that my character will stutter when moving. (I'm using the character controller along with the input system)
I checked the input system debugger and all I'm seeing is the key for movement being, seemingly, randomly triggered multiple times. All I am doing is leaving my finger on that key ('A', in this instance.). If I let my mouse trigger movement this doesn't happen. I don't know what to make of this. My keyboard functions fine, and yet it seems to be the issue...(?)
Ty i was looking at the 2.5D turn based RPG from Gamedev
yeah gamedev has a lot of good resources i use them a good bit for misc things
{
textTomato.color = Color.yellow;
}
if (amountTomato == 200)
{
textTomato.color = Color.yellow;
}```
is there a way to fit both of these into one if statement
{
textTomato.color = Color.yellow;
}```
thank u
that shoudl be right anyway since they both end up doing the same thing
your welcome
so basically the || is to do more than one?
|| is OR in programming
good to know thank yu
is therea way to just straight up make it if its a multiple of 100? or do i have to type them all like that
modulus operator? %
so like if amountTomato % 100 equals 0 the number is a multiple of 100
should work
{
textTomato.color = Color.yellow;
}```
something like this
ill try now ty
it works but i only want the number '100', '200', etc to be yellow, the ones after that are also yellow
There are a bunch of tutorials for Tactics RPG, turn-based strategy RPG, and isometriRPGsPG on YouTube . . .
ohhhh
{
textTomato.color = Color.yellow;
}```
this is rough cause im tired but that should make it to where it makes sure its a multiple of 100 and that its greater than 100. so 200 should work but 201 shouldn't
if you need me to break it down further i can
the other numbers are still yellow
I couldnt really find any honestly
ah i forgot something
If you only need 100 and 200, it's easier to just use the OR operator for both values . . .
she said mutliples of 100, going up to infinity assume
nah that was just an example i wanna do it for every hundred, 100, 200, 300, and so on
you need the other condition.
{
textTomato.color = Color.white; // default color
}```
well its supposed to say else at the top
Then just use an else that sets it to the default (other) color . . .
add that after the other code i sent
ye i got it just took a sec for my brain to process what he was wanting since im tired lol
If it's a multiple of 100, turn yellow; else, turn default . . .
{
textTomato.color = Color.yellow;
}
textTomato.color = Color.white; // default color``` outside like this?
no, that second one should be wrapped in an else statement
ohh right, im slow ๐คฆโโ๏ธ
{
textTomato.color = Color.yellow;
}
else
{
textTomato.color = Color.white; // default
}```
all good ๐
works like a charm tysm
np
one last thing would there be a more efficient way of doing this
{
textTomato.text = "1K";
}
if(amountTomato >= 1100)
{
textTomato.text = "1.1K";
}```
yes ive actually seen very similar to this before gotta remember how to do it, you can use the .ToString to format decimal places
one sec
oo okay
{
float displayValue = amountTomato / 1000f; // convert
textTomato.text = displayValue.ToString("0.#") + "K"; // format
}```
should be like this so if amountTomato = 1000 its 1K, 1100 = 1.1K, etc etc
ill tset it now, might tatke a while for me to get to 1000 tho ๐ญ
sorry im so used to adding comments when i make code its just habit lol
nah it helps me i like it
i mean you ARE the game creator, you could do it manually
why did my discord just crash when i clicked on your profile wtf
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
โข Collaboration & Jobs
true
make a secret button on a keyboard that you dont specify that actually makes it go up by like value ^ 5 or something instead of doing whatever the game mechanic is
fun easter egg
Google/YouTube search . . .
wait the one for the yellow just randomly stopped working
welcome to the wonders of game development
worked 5 min ago changed nothing now it doesnt work
normally breaking something then restarting unity fixes it, for me at least
i fixed it, it was because i tried adding the same tex tcolor thing but for 1000 but i forgot that the else statement said keep the color to white
if that makes sense
brain said its too late to process that but my eyes understood what you said
๐คท
{
textTomato.color = Color.yellow;
}
else
{
textTomato.color = Color.white; // default
}```
tried adding this but this
```textTomato.color = Color.white; // default```
stopped the 100 text from turning yellow
couldn't you put the K inside the format string
yes this would make 100 not pass the condition
100 % 1000 is 100
im failing math
you don't need to make a separate thing for multiples of 1000 if you're going for the same result
oh
all multiples of 1000 are also multiples of 100
yeah im definetly failing maths
i mean you could yeah. doesnt really make a difference
at least i dont think it does
how do i constantly update a text to be the same amount as an int
Ive seen many of these. I was hoping for something with more reading involved. Reading kinda helps explain some more of the advanced stuff better. Appreciate the search tho, thanks.
use Update()
ohh right thnaku
textTomato.text = amountTomato.ToString();
in Update()
if your referring to those same variables that is idk
im learning more from the people in discord than youtube tutorials help
yeah u got it
would technically be more efficient
also like, that's the point of format strings, to see your value in context
sure
working?
i dont thin kso
so it SHOULD be white, no?
im talking abt the 1.1k thing
then you would assign the text to the result of the formatting, not a direct stringification
the ToString("0.#K")
{
float displayValue = amountTomato / 1000f;
textTomato.text = string.Format("{0:0.#}K", displayValue);
}
else
{
textTomato.text = amountTomato.ToString();
}```
?
sorry im back
ill try
it still shows the number
Call a method to update the text when the value changes . . .
https://pastebin.com/KNWqdkrn this is all my code
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.
make sure you've saved and restarted
couple things. seems that theres no need for update since the logic is already handled in Tap(). only thing i can think of is basic stuff like make sure the textTomato reference is assigned properly and make srue the Tap() function is actually being called
why do i have to set my tile anchors to 0.5 instead of 0 or 1? did i mess something up? (when i dont, the tiles arnt aligned properly
btw, im going to bed, so hopefully someone else can help or you can just message me later.
alright thanks for the help btw i learnt alot
remove update() code, it is called every frame
That doesn't really hurt the application, but in their case I don't see why it can't just be updated when Tap is called
The UI logic should probably be seperated in general from the actual behaviour
is there a way to make a rawimages size expand when hovering over it
im guessing it would be done with an event trigger?
not a code problem; but it's probably with how you've set up your pivots
how can i create a prefab of a structure in a tilemap (like a box) and be able to paste those boxes through code into the same tile map?
right now i am able to create tiles through the tilemap.settile function, but is there ways to paste entire structures into the tilemap without creating the structure in code?
you can store your structure's tiles in an array and use SetTiles with it
there is no 3D Perlin noise in Unity. I am wondering if it's possible to achieve it using something like this:
val = (perlin2d(x, y) + perlin2d(x, z) + perlin2d(y, z)) / 3๐ค
I dont think that could work. The technical reason is because (2d) perlin noise creates a random set of noise values, and those values are used to find a gradient (which is basically just a direction to point in)
as its 2d those lines wont point up into the 3rd dimension. so its not able to understand what values are above or below
how do i make my circle overlap all only affect the player only once per animation
private void FixedUpdate()
{
Collider2D[] colliders = Physics2D.OverlapCircleAll(posHit.position, 1f, lm);
if (colliders.Length > 0&&en.anim.GetBool("attack")==true)
{
c.health--;
}
}
Is this something like in games where the player gets hit, then the sprite flickers on and off to show how you cant get hurt for some time, then when that animation ends you can get hurt again?
Consider using Physics2D.OverlapCircle if you call Physics2D.OverlapCircleAll in (Fixed)Update because you are now allocating an array very often for no reason
basically posHit is the sword transform. and the enmy just swings it in it's anim. now if i run this my players health drops to 0 in one swing becuase of c.healt--; being called repeatedly
ill try that
it works but the original problem still stands
Sorry, not sure what your problem is from the question
Just wanted to point out the performance issue
c.health-- is called repeatedly in one animation play. i only want it to affect the player once per animation
Sounds like you need invisibility frames?
I'd say add a timestamp when the hit happened using Time.time and check if a certain amount of time passed before deducting health again
See here, and also a good example of using a timestamp https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Time-time.html
The example does the same, but instead delays firing
also since it is time elapsed would time.deltaTime be a better fit?
bool PlayerIsHurt = false;
update() {
Collider2d[] colliders = ...;
bool enemyValidAttack = colliders.Length > 0;
//this condition must be true when the enemy is currently
//attacking the player, and that the attack will definitely
//cause the player to lose health
//i.e player has a sword through them right now
if(PlayerIsHurt == false && enemyValidAttack == true) {
//player is not currently hurt, but the enemy has attacked
health--;
PlayerIsHurt = true;
}
if(PlayerIsHurt == true && enemyValidAttack == false) {
//the player has been hurt in the past few moments
//but now the enemy is not currently attacking
//so reset the hurt bool, this will allow the player to be attacked again
PlayerIsHurt = false;
}
}```
No need because you don't use a system that is on a per-frame basis
Only if you were incrementing some timer manually, but a timestamp is set once when hurt
And Time.time is frame-independent
i see
@burnt vapor I wouldnt suggest they use the code, just as a way to see how you'd cancel something from occurring multiple times
Sure, but your code allows the player to basically hug an enemy without it ever registering twice
Or better yet, basically any collideable object that hurts. As long as you hug at least one, the player is invincible
no it would mean if you get hit by a sword, only the first time the sword enters the collider, is when the first if statement gets called. next frame when the sword is still inside, the player wont get hurt, as the health-- conditon cant be entered again
only when the sword then leaves the player, would that open the second if statement up to be entered, allowing the first if statement to be entered once again
this was actually my first trial fix for the problem but it didnt work
It would not, there is no proper way to handle the colliders like this
@gilded canyon actually you know what? why not disable the collider when the hurt animation is active
this works thanks!
Games have always enforces invincibility frames
no collider means no more valid hits
Or you know, use invincibility frames like all games do ๐ซด #๐ปโcode-beginner message
its not a collider its a overlapcircle. and if i did do that i have to renable it via animation event at the start of every hit but it still doesnt work
Why would you make it more complicated with juggling colliders when you can literally just make the player invincible for a frame
Constant damage is bad feedback anyway
already did!
No I get it, just want to point out that it's a pretty basic feature
ah, I assumed overlapcircle was doing something more collider/body related
I can understand that maybe you can also disable the sword from hurting the player, but in that case I would advice you do a reference check or an instance id check on the weapon against a player
Don't disable anything, because you limit yourself in what is possible (example, you can't hit multiple objects with the sword)
also if yall dont mind me asking wht would be a more fun solution for stealth. hiding behind and moving with a prop for a disguise. or something like the disguise kit from tf2 where you can change character with a mouseclick
Sorry, I have no idea
I guess it also depends on the actual game you make
i want to make an ability (3D) that creates an expanding spherical AOE. But i dont know what it should do on the ground or in corners. i guess i'm looking for something like flood fill, but the result should resemble a sphere or a cylinder.
should it pass through walls?
if yes then you could just ignore the whole issue of collision
Make a set, physics.overlapsphere and add all hits within it, then take a box that bounds the combat area, physics.overlapbox that and intersect hits with the sphere hits in the set.
typically, 3D games that donโt use a grid ignore that kind of thing and make walls thick and rooms rather spaced out
[Header("Bounding Box")]
[field: SerializeField] public Vector3 BB_Origin { get; private set; }```I understand how to resolve the error (removing `get;set;`), but why is it an error to begin with? Without the attribute, the property shows up in the inspector just fine
Does this script have IDE in it ?
Because you're applying the attribute to the property, not the backing field
-[Header("Bounding Box")]
+[field:Header("Bounding Box")]
oh, interesting!
It is very unclear what your question is
Also, your !ide is not configured. Please configure it
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
โข :question: Other/None
I want to know if IDE is available in my script since I downloaded a new version of visual studio that I linked with unity
This is Visual Studio Code, not Visual Studio
Your phrasing makes absolutely no sense
the IDE is the thing you write code inside, could you explain what you mean by this?
I assume they are asking if they have it configured from their phrasing, in which case it's not
yeah, but the usage of "IDE" is causing some miscommunication here
Hence the phrasing
@minor radish do you mean, "will I be able to open up this file inside an IDE"?
No what I mean is that "is there something which guide to do my script ?" since as far as I know about IDE it's something that makes the task easier to do in a script but it looks like I don't understand it at all.
hi im currently trying to get an enemy to move around the map and ive got all the code and followed this tutorial up to the part where he talks about baking which for some reason isnt allowing me to bake properly and therefore not allowing the enemy to move around https://www.youtube.com/watch?v=UjkSFoLxeswv
Yes, that's intellisense. Please follow one of the links to set up your !ide ๐ซด #๐ปโcode-beginner message
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
โข :question: Other/None
In your case for VS Code, though I advice you download Visual Studio or Rider manually as it is not as clunky
iwas wondering, how did you determine that his IDE is not set up correctly
Lack of syntax highlighting
baking is about 4:40
in VS it is obviusly though in VS code not sure.
In VSCode's case it does a good job on trying to do it right, but it's clear it's not configured when enums like KeyCode and Vector2 remain bland because it doesn't know wether it works with a variable or an actual enum
In the case of VS you can often see misconfiguration because it simply doesn't know what MonoBehaviour is, but VSCode can support any language so it doesn't error as quick and it makes a lot of assumptions, hence why it knows Monobehaviour and RigidBody2D are probably classes somewhere
oh okay
try regenerating project files if nothing works
there are a lot of signs one of them is that u can see the number of referrences of each variables and methods above them, if thats not there its a pretty good sign that ur ide isnt properly setup
I'm downloading it currently I hope it will work
so you switched to VS from VS Code
no he switched from VS code to VS
VS code would also work if u set it up properly and its also lighter.
he was using vs code before when he posted the screen shot
ya but he hadnt set it up properly
u need intellisense extension unity debugger and unity extension, and then u need to regernerate project files from unity project
What's the difference?
is there a maximum to how much code you can sent in here at once ? Like is it against the guidelines if i send 100 lines of code?
Set up the Unity workload and set VS as the external editor. Then it works.
No, but in terms of readability it is preferred if you use a paste site for much code
well code wise nothing but i prefer vscode so i am kinda biased
Also for mobile users because Discord formatting sucks on mobile
VS and Rider will always be better for C# development
When you subscribe to public event Action testEvent; like this.. testEvent += VoidMethodCalled is the method VoidMethodCalled that subscribes to the testEvent an Action itself?
No, an action is a wrapper object around a method, that can be used to call it by reference. Itโs called a delegate and is a concept similar to a function pointer.
but doesn't testEvent do exactly that?.. When testEvent?.Invoke(); is called it loops through its subscribed list and calls their methods
{
anim.SetTrigger("Walk");
}``` any reason why this wont work?
it says something about the || but idk what else to use
or do i have to do them all seperate
dont think you can combine them and you should use KeyCode.W
Please learn basic C#
im trying :)
alr all good
Seriously, if you can't see why this is invalid syntax I strongly recommend you try some basic C# projects first
Yep ari go relearn C#
damn bro mb
There's something that comes close called pattern matching, but it won't work with Input.GetKeyDown anyway
didnt know ur life depended on my code ๐ญ
an event is a C# language construct that does what you say in principle, however you cannot fully reason about how c# works in terms of C# actions and objects
Ur the one wanting help, no need to be like this or we throw you out
It's not, and I'm confused why this is your response. I am suggesting this to you because you are going to have a very tough time with Unity if you have to learn C# as well
Input.GetKeyDown("W") returns a bool, ("A") doesn't (it's a string), that's why it doesn't work. || only works for two bools
thanks
When you do
testEvent += VoidMethodCalled;
it is shorthand for
testEvent += new Action(VoidMethodCalled);
So the answer to the question "is the method VoidMethodCalled ... an Action itself" is no, but you implicitly create an Action that references the method.
I feel like any attempt to explain the problem just ends up making it even more confusing
nah he just fixed it for me
it works now
If you think too hard about applying c# language rules to how c# actually works you run into some contradictions
Share your code
may we see how you did it?
Doubt it does, but sure
sounds right
Not the correct apporoach, but should work
What I am really trying to do is simply wrap the event += MethodToCall and wondering if this is incorrect.. it seems to work
public void AddListener(Action d ){
notification += d;
//extra code here
}
Sure you could use input mappings but getting things to work should be the first step when learning to code
@cloud matrix please watch more C# tutorials, before you get more issues like this, there are webtools, YouTube Vids, etc for C# learning
Yeah other thing is why they using the old input system
Prolly a horrible out of date tutorial
TBH Unity's old input system is very limited and horrible so checking multiple keys will never look good
This works, itโs called a higher order function where you pass in parts of itโs implementation as an argument, and it does work because of the wrapper (delegate) being a reference to some other method.
Yes, this is the correct approach.
You can also do this by overriding the add and remove of an event property:
private Action notification;
public event Action MyCustomEvent {
add {
notification += value;
// extra code here
}
remove {
notification -= value;
// extra code here
}
}
Which can then be used as a normal event:
myClass.MyCustomEvent += VoidMethodCalled;
thanks I think I got it now
does anyone have any ideas how to make sure that if this return true, OnPuzzleCompleted is called ?
// If the puzzle is complete and not already flagged, call OnPuzzleCompleted.
if (!isPuzzleComplete) {
isPuzzleComplete = true; // Mark the puzzle as complete to prevent multiple triggers
OnPuzzleCompleted(); // Trigger the completion logic
}
return true;
} i have tried this, but it just makes the game constantly load between different scenes
Guys Iโm making 2d platformer and when I jump on a platform my character is always rolling and bouncing around and the jumping is very glitchy pls help
freeze z rotation
if what returns true?
CheckCompletion
u could subscribe it to an OnCompletion event and call it at the end
K this is what it looks like
did u freeze z rotation?
I have loop time set to on in the animation settings but it doesnt loop any help
{
anim.SetTrigger("Walk");
}```
What is pieces[i].name? Why is it a string and not an integer? This comparison is weird
If it's guaranteed to be an integer, why not use an integer?
Does it work now is the phrasing here
wait yes it works
check if autocomplete and code snippets work
go to the constraints of ur player's ridigibody 2d and freeze rotation for Z axis
HEy
Where do i get help
Bro i will not read all this
i took 5min reading ruels
How to check that ?
type in Rigidbody. and if it shows the suggestion for completing it then autocompletion is on
Yes, this is now configured. Good job ๐
type awake and if it suggest a snippet then snippets are on
i want to use the new input system to move the char
what's the best way to start learning unity ?
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #๐โfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
!learn or check pinned messages in this channel
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
!learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
thx
Thank you for you're help
dude u could just watch a tutorial for this .... u need to set up an actionmap and charachtercontroller
it's simple Question
But the answer is not that simple
It is thank you
I did
This channel is not for spoonfeeding. Attempt to implement the new input system and feel free to ask for help when you get stuck
How to make the char move
This is something you can just look up. Right now you probably haven't even tried it
In this Unity tutorial we will explore the ways the PlayerInput component can help us to extremely quickly and easily handle the input using the new input system package. I personally use it all the time - I don't think there is a quicker way to use the new input system, so I hope you enjoy the video and learn something useful! :)
Unity Docs ab...
i did but the tutorials was for top down movement or full 3d movement
Learn how to use Cinemachine and the new input system to make a First Person Controller in Unity!
แ
Get the full Source Code Bundle to my Unity Tutorials ๐ค
https://sam-yam.itch.io/samyam-full-source-code-to-all-videos
**DO THIS โบ There is an easier way to override the old input system values in cinemachine using the Cinemachine Input Provider (...
and iam not that good at english
do this is is for fps pov
If your player moves side by side, it's better to have Left/Right (A/D) as one axis, and the jump (Up or Z) as another, instead of a single 2D Vector for the full WASD
From your screenshot it seems that you're in 3D, but always using a fixed perspective, like in 2D
Alr
i am assuming thats because he doesnt know how to setup cinemachine yet
i want controlls like in super smash bros if you know it
Yeah so 3D but viewed from the side
So i just use 2d input system
Something like this yes
if u only need a single set of controls u could just use unity's old input system, it would be simpler
No, you should not use old deprecated legacy features just because it's easier
i also thought that but a mod told me yesterday that it isnt depricated and that its the original input system now
Plus the new one is enabled by default IIRC, so it's more hassle to re-enable the old one
I know, I already modified my message to clarify it's not actually deprecated before yours
It's legacy, like the old text system. Just like with that, you should not use it
It just remains for backwards compatibility
Ok that works but my jumping is very glitchy look
post ur jumping code for movement and jumping
Alr
also learn to screen record dude
Iโm on my phone sry
its fine for now
So i have the Problem that when i shoot at the player he is losing damage but i see his health and mine at the same time
because you have 2 standalone instances of TestMeshProUI?
if there was one you would have one
how to format code
!code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class MonkeyScript : MonoBehaviour
{
public float speed;
private float move;
public float jump;
private Rigidbody2D z;
public bool isJumping;
//scale values of monkey
float zy = 0.56f;
float zx = 0.53f;
// Start is called before the first frame update
void Start()
{
z = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
//movement
move = Input.GetAxis("Horizontal");
z.velocity = new Vector2(speed * move, z.velocity.y);
//jump
if (Input.GetButtonDown("Jump") && isJumping == false)
{
z.AddForce(new Vector2(z.velocity.x, jump));
}
//change directions
if (move > 0.01f)
transform.localScale = new Vector3(zx, zy, 0);
else if (move < -0.01f)
transform.localScale = new Vector3(-zx, zy, 0);
}
private void OnCollisionEnter2D(Collision2D other)
{
//ground check
if (other.gameObject.CompareTag("Ground"))
{
isJumping = false;
}
}
private void OnCollisionExit2D(Collision2D other)
{
//ground check
if (other.gameObject.CompareTag("Ground"))
{
isJumping = true;
}
}
//attack
public bool canAttack()
{
return move == 0;
}
}
here it is
gimme a sec
alr thanks man
did you not read or just not understand the bot message?
i formatted the code
Large Blocks should use a paste site, yours is a large block
instead of doing getbuttondown and getting it from axis just try getkey and use keycode
if it still doesnt work try changing the ground check to use a raycast instead
ok i am gonna eat and then try thanks
also do u know how i can split up my monkey character to animate later by chance
what do u mean by split up?
like split arm and legs for example
do u need to split it for animation?
yes
{
anim.SetBool("Walk", false);
anim.SetTrigger("MoveShoot");
}```
any reason why this doesnt work?
basically tryna make it so if ur moving and shooting the shooting anim plays instead of the moving one
then just make them different sprites and put them under a empty gameobject
okkk
I used code at the end and it worked
im still tryna learn raycasts tbh
What doesn't work?
Does it call the code?
Does SetBool work? Does SetTrigger work? More context please
If it's the wrong animation then it's probably pointing to the wrong animation?
This code is valid so idk what else to say
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.
ill show a vid
okay wtf nevermind it just decides to work now ๐ญ
just saying but try getmousebutton instead of getmousbuttondown and see if it works
yaeh i had to change getkeydown to getkey bc when i was pressing two buttons and then letting go of the first one the animation stopped, so this would probably work thx
i am a bit confused about the working of it thats why i stopped using the old system
the documentation says that getmousedown is only supposed to return true on the instance that the mouse was clicked but most of the time it still returns true as long as mousbutton is pressed down
imma learn how to add gun cooldown brb
why that box just on air?
Nope it doesn't, it returns true for the first frame the button is held down. So if you have two or more of the same GetButtonDown() following each other in Update, then they'll all return true. It's not setting it back to false when you call the method for the first time
ya i mean thats what it says in the doc so ari's function here doesnt work
can u show the jump component and speed component scripts?
that just data script
try restarting the project
can i somehow drag this into this? they are in diffrent scenes
GameObjects are bound to scene they are instantiated in, you cant cross reference. You can use prefab or on scene load look for given gameobject in other scenes. So you can store gameObject name and look for it later, there are other solutions too.
Why are they in different scenes anyway?
Is this some save object you want to save or something?
How to set frame rate to unlimited?
Android
Is it Application.targetFrameRate = -1; ?
even if that is possible i would not do that, it is recommended to limit the fps on mobile to save battery
It's in player settings
30, 60 and unlimited
Default will be 60
Oh, so there is no other way huh
you must pick a specific framerate if you want anything higher
Alright, 90 then
You should figure out the display's refresh rate and use that
You, there is no unlimited
I think that's what Pokemon Go does, for example
the default is 30, and there's a setting to use the native refresh rate
Then that's going to be the third option
Thanks
I set the frame rate to the device refresh rate as otherwise it will be 30 by default
So like this? ```void Start()
{
int refreshRate = Screen.currentResolution.refreshRate; // Get native refresh rate
Application.targetFrameRate = refreshRate; // Match it
}
Something like this yea I forget it's in many projects that in work on.
Hello. How can I make my jump script synchronize with the jump animation? I am using the unity input system for character movement
You can use animation events to get a callback at a certain point in the animation
void Flip() { facingRight = !facingRight; Vector3 Scaler = transform.localScale; Scaler.x *= -1; transform.localScale = Scaler; }
if (facingRight == false && moveInput > 0) {Flip();} if (facingRight == true && moveInput < 0) {Flip();}
this code is doing nothing for some reason
it started doing this after adding animations to do with scale does anyone know a fix
Did you check that Flip is getting called, with a Debug.Log? for example?
Perhaps your animations are controlling the scale of the player
Do you have an animator that could be modifying the scale?
yes i have done
yes i do but i dont know the way around this sorry im a beginner
ive been stuck on this for a while ive searched everywhere for solutions
how do i make the animation play flipped when the character is flipped and vice versa basically what im asking
You can check if this is happening by trying to change the player's scale while the game is running
just go in the inspector and type something in
if the value immediately resets, then the animator is controlling it
Remove the scale keyframes from the animations that your character uses, i suppose
i want to keep the animation though i just want it to play flipped when character is flipped this must be possible?
I didnt say remove the whole animation, just remove the keyframes that modify your scale
Could just remove the X scale and keep Y if you want
ok i will try this
I'm pretty sure the animator can't control a single axis like that
You can set a sprite renderer to flip on the X axis using the flipX property
This wouldn't cause all of your child objects to flip, though
i removed all keyframes from x axis and its still stuck at its default scale
alternatively, consider setting up your character like this
no good
- Character
- Body <-- animator, sprite renderer
- Hitbox
- Whatever
- Body <-- animator, sprite renderer
you can freely manipulate the Character object
You right
Body (and all of its children) will be affected by whatever the animator does to its scale
ok makes sense i will try it
perfect thank you for this
This is how I set up most of my prefabs
nevermind hes teleporting to the mirrored side of the screen wtf
Your body is probably positioned far away from the root right now
make sure its local position is zero
should the rigidbody be on the parent object or still on the body
done this
It should go on the parent object
along with, say, the character movement component
Hey, i think i'm understanding vector3.project incorrectly
Can someone give me a hand here?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
i'm trying to project the green sphere onto the green line based on the red sphere's movement
it seems to be projecting correctly, just at an offset, i suppose
You're getting a direction, but you're missing an origin
Subtract the origin of that green line, do the projection, and then add the origin back
That... works, although i don't understand why that works
It doesn't make sense to project a position
A position is a point in space. It doesn't have a direction, really
That i understand (which honestly makes Vector3 confusing to me sometimes)
The problem would be more obvious if we were using homogeneous coordinates, actually
they're 4D points
the 4th component is 1 for a position and 0 for a direction
it winds up neatly making sense
[3,0,0,1] - [1,0,0,1] = [2,0,0,0]
you can add directions to each other, and you can add a direction to a point
but you can't add two points together, for example
Hold on, is this how they actually work or jsut a quick abstraction you're doing to help me get it?
I get there are direction vectors and positional vectors
position is easy to get, simple coordinates in space
but direction is a bit tougher to visualize
check out something like https://www.tomdalling.com/blog/modern-opengl/explaining-homogenous-coordinates-and-projective-geometry/ for a more in-depth look at that
but yes -- if you're using 3-vectors in 3D space, positions and directions aren't distinct
you can interpret the same value as both a position and a direction
Suppose we want to project a position of [10,1,0] onto a ray in the [0,1,0] direction whose origin is at [10,0,0]
If we just do the projection naively, we throw out the X component completely
the result is a position of [0,1,0]
By subtracting the origin before projecting, we get just the direction between the origin and the point
which makes sense to project
and then we add the origin back to get a position again
[10,1,0] - [10,0,0] = [0,1,0]
projecting [0,1,0] onto [0,1,0] does nothing
[0,1,0] + [10,0,0] = [10,1,0]
and that's the result we actually wanted
it does though?
in 2d, projecting a point P onto a line L is drawing a line that's perpendicular to L and passes through P, then taking the point P' as the intersection of that line and L
in 3d, same with a plane instead of a line, no?
You can do it, but does it make sense?
yes?
if you look through the plane orthogonally, where does the point end up on the plane
yes, and you can also multiply the point by 3 trillion, but does that make sense? (:
if you need to, yeah
The goal is to find a point on the line based on the position of the red sphere
are you talking about "making sense" for the actual problem, or just the operation?
The former.
ah, ok. mb then, thought you meant the latter
Projecting the position of the red sphere onto the direction of the line only makes sense if the line originates from the origin
which line?
(because in that case, subtracting the line's origin does nothing anyway)
the green line
you wouldn't project onto the direction of the line, you'd project onto the line
doesn't have to be from the origin
well, sure, but you do that by subtracting the origin of the ray from your position, then projecting that onto the direction of the ray
(and then adding the ray's origin back in)
Vector3 projectedPointOnNormal = Vector3.Project(pointOnPlane, axisHandler.transform.up);
This is what the problem code did.
The correct code would be...
Vector3 result = pointOnPlane - axisHandler.transform.position;
result = Vector3.Project(result, axisHandler.transform.up);
result += axisHandler.transform.position;
you're just reassigning result there?
i think i missed too much context to really think about the situation lol
Gizmos.color = Color.red; Vector3 pointOnPlane = ray.GetPoint(enter); Gizmos.DrawWireSphere(pointOnPlane, 0.1f); Gizmos.color = Color.green; Vector3 projectedPointOnNormal = Vector3.Project(pointOnPlane - axisHandler.transform.position, axisHandler.transform.up ); Gizmos.DrawWireSphere( projectedPointOnNormal + axisHandler.transform.position , 0.2f);
This seemed to work
i dont get why id want a result += there
it's offseting by axisHandler.transform.position
you're trying to snap to a point on a ray, correct?
oh, you did the same thing as I did, just without modifying projectedPointOnNormal
Something(foo + bar)
is identical to
foo += bar;
Something(foo);
it's just that your code winds up with a misleadingly-named variable
projectedPointOnNormal contains the projected vector -- which tells you how far away from the axis handler's position your point should be
The proper name would be projectedVector or offset or something like that
Vector3 rayOrigin = axisHandler.transform.position;
Vector3 rayDirection = axisHandler.transform.up;
Vector3 originalOffset = pointOnPlane - rayOrigin;
Vector3 projectedOffset = Vector3.Project(originalOffset, rayDirection);
Vector3 finalPosition = projectedOffset + rayOrigin;
Perhaps that makes it more clear?
while storing single point positions in vector3 i like to visualize them as position vecotrs, it helps withe the understanding
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Example : MonoBehaviour
{
private CharacterController controller;
private Vector3 playerVelocity;
private bool groundedPlayer;
private float playerSpeed = 2.0f;
private float jumpHeight = 1.0f;
private float gravityValue = -9.81f;
private void Start()
{
controller = gameObject.AddComponent<CharacterController>();
}
void Update()
{
groundedPlayer = controller.isGrounded;
if (groundedPlayer && playerVelocity.y < 0)
{
playerVelocity.y = 0f;
}
Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
controller.Move(move * Time.deltaTime * playerSpeed);
if (move != Vector3.zero)
{
gameObject.transform.forward = move;
}
// Makes the player jump
if (Input.GetButtonDown("Jump") && groundedPlayer)
{
playerVelocity.y += Mathf.Sqrt(jumpHeight * -2.0f * gravityValue);
}
playerVelocity.y += gravityValue * Time.deltaTime;
controller.Move(playerVelocity * Time.deltaTime);
}
}
What do I need to change here to make my character move? I just need a simple wasp jump control
seems like the movement should work fine, but this just makes no sense
gameObject.transform.forward = move;
I just copied and pasted the unity example
oh wait yeah i see what that's doing
there's no mouse movement there
so what's not working with it
well the character just doesn't move at all
have you set the input axes
gravity and all the collision boxes work, just doesn't move
and make sure you've saved and set everything
no? idk? I legit just created a new monoscript, pasted that, saved and tried to run the game to see if the character moves
did you add the script to your player object
!code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ok so start debugging, try logging out move for example
what does that mean?
Debug.Log(move)
in the Update function, after you've set move
uh there are these errors when i run the game
void update?
yes that's called a function
that wouldve been helpful to know...
what's line 21?
show the stack trace
do blank spaces count as a line?
yes every line counts as a line
ok
go into your ide and look for the line that's labelled 21
ur editor should already have lines numbered
Line 21 is the line labeled "21" in your code editor
line 21 is
groundedPlayer = controller.isGrounded;
I just use notepad ๐
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
โข :question: Other/None
wow first time i have heard that
can u just check if u added character controller component to your player?
The most experience in coding I have is editing a few lines of lua for my fivem server lmfao
I have
ok so controller is null. do you have a controller on the same object the script is on
oh wait
oh you shouldn't have one since Start is adding one
enterprise, pro or community? which is best for me?
Community, the other editions are paid
are you enterprise/pro? no? then community
private void Start()
{
controller = gameObject.AddComponent<CharacterController>();
} Make this controller =GetComponent<CharacterController>();
add component in editor not in script
where? how?
in the inspecter click on add component then type in character controller
I'm not good at this unity stuff ๐ญ
click on this add component
I already have the CC
okay then change the think in start
this
just 1 min pls while I install this IDE thing
ya u need to configure the ide after installing it so its gonna be more than 1 min, take your time
oh god lmfao
private void Start()
{
controller =GetComponent<CharacterController>();
}
replace the start with this when ur done
well u still need to configure the ide to add intellisense and autorcomplete and stuff.. but for now just try running ur project and see if it works
or if atleast the errors are gone
okay ๐
it's nearly working... whats the best way to share a vid here?
well u can record it and share video
no other way
if u have obs its quite easy
https://getsharex.com/ heres a good video recorder for little snippets and stuff
as you can see the character does like a break dance when I don't press anything, and it moves like a compass, w = north.ect I need a movement system where, where ever the the camera is facing is forward and well to be able to move the camera. I need a gta style movement system ygm?
u need to freeze rotation on x and z axis
click on the player and in the rigidbody of the player under contraint rotation check the X and Z axis
ok
awesome breakdance fixed, does anyone know where I can find a camera control script so it moves with my mouse, and how to make forward be where the camera is facing so movement is less compass like
you should not have both a rigidbody and a charactercontroller on the same object, they will compete to control transform
have you considered learning to make it yourself?
!learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
really? 2 days ago I was told I needed both because I kept falling thru the ground
the example given in the charactercontroller docs is just that: an example
it probably does not do what you want it to
ya u need both but not on the same object
yes I'm just tryna get a few example scripts so I have a foundation to work with
make an input manager script and refference from there
you don't need both, no
wdym ? how do u work without ridigbody?
by..using the character controller
there's a ground check in the charactercontroller example code
the character controller will already stop you from moving through colliders
isnt it easier to have a rigigdbody on the player and then character controller on its empty parent?
that sounds very weird
the player would...fall down, away from the parent
so you'd have this player object rattling around like a loose screw in your PC case
@lucid quiver do you think these scripts will do what I want? idk how to read code yet
https://discussions.unity.com/t/third-person-camera-movement-script/783511
the child would respond to physics while the parent moves around it
start at !learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
hmm ya thats true now that i think about it
u literally dont even need much scripting if ur using cinemachine
look up cinermachine doc
but it's only compatible up to 3.1.2
3.1.2 is the latest version of the package
that version is available in unity 2022.3 onwards
putting a script on a regular camera for this stuff is gonna cause a decent stutter in the camera
ah
no? not if you make it correctly
u can add smoothing to it if u want
well i tried that a some days ago and had problems so i posted it here and a mod said that its better to use cinemachine for it
i tried a lot of stuff and still had stutter so i just gave up
and implemented cinemachine
No, LookAt says 'None'
nvm noticed my mistake
yea idk what to set that too, the camera or my character
I'm guessing you want your Camera to LookAt your Character
post an ss
Something about my game's resolution is off. In windowed mode the game looks good, but in full screen the edges are jagged
Another thing is that to take a pic of the jagged graphics I had to take a pic with my phone, because if I take a screenshot it looks like in the windowed version
Maybe it has something to do with the monitor resolution settings?
What resolution is the game set to?
What resolution is the display set to?
I just did that and now the character is zooming backwards infinitely
Ok, why?
better, maybe, but that doesn't mean you can't do it without cinemachine
cinemachine works by controlling the camera anyways
When the user enables fullscreen in the settings, I run this code
Screen.SetResolution(Screen.currentResolution.width, Screen.currentResolution.height, true);```
Also in the player settings I have enabled " Default is native resolution "
You're setting it to fullscreen but then reducing the resolution to whatever it was before...
yes but i tried a lot of things and couldnt stop the stutter if u have a better code for it would be helpful
Shouldn't Screen.currentResolution.width be the whole screen resolution?
If the monitor is 2560 ร 1440 shouldnt it return 2560?
idk
are u using cinemachine or just regular camera?
it was most likely a problem with your setup and not your code, as your code looked fine to me
unfortunatly the camera script isn't moving with my mouse
i tried vsync so idk what else there is to try
where is the script?
below player move in the character's inspector
no i mean the actualy script
need to see the code
!code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed * Time.deltaTime);
transform.position = smoothedPosition; // basic smoothing using `Lerp`
triple tick for block.. single tick for single line of code
'''cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraMove : MonoBehaviour
{
private const float YMin = -50.0f;
private const float YMax = 50.0f;
public Transform lookAt;
public Transform Player;
public float distance = 10.0f;
private float currentX = 0.0f;
private float currentY = 0.0f;
public float sensivity = 4.0f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void LateUpdate()
{
currentX += Input.GetAxis("Mouse X") * sensivity * Time.deltaTime;
currentY += Input.GetAxis("Mouse Y") * sensivity * Time.deltaTime;
currentY = Mathf.Clamp(currentY, YMin, YMax);
Vector3 Direction = new Vector3(0, 0, -distance);
Quaternion rotation = Quaternion.Euler(currentY, currentX, 0);
transform.position = lookAt.position + rotation * Direction;
transform.LookAt(lookAt.position);
}
}
'''
damn
` not '
nope, wrong key.. its the one above ur Tab key ๐
ohhh
Depends on your keyboard layout
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraMove : MonoBehaviour
{
private const float YMin = -50.0f;
private const float YMax = 50.0f;
public Transform lookAt;
public Transform Player;
public float distance = 10.0f;
private float currentX = 0.0f;
private float currentY = 0.0f;
public float sensivity = 4.0f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void LateUpdate()
{
currentX += Input.GetAxis("Mouse X") * sensivity * Time.deltaTime;
currentY += Input.GetAxis("Mouse Y") * sensivity * Time.deltaTime;
currentY = Mathf.Clamp(currentY, YMin, YMax);
Vector3 Direction = new Vector3(0, 0, -distance);
Quaternion rotation = Quaternion.Euler(currentY, currentX, 0);
transform.position = lookAt.position + rotation * Direction;
transform.LookAt(lookAt.position);
}
}
yay
true.. i just assume no one has different keyboard layouts than me.. ๐คช
ty guys!
I believe most people have qwerty
Still there are different regional/cultural variations of qwerty, like I have
Special characters are in different places
okay
Yo
tbh this is someone elses code that I just C&P'd
well of course if you are using a custom keyboard
we're not judging.. just letting u know
yea i get that, just saying idk any of this yet. I'm gonna get on that !,learn thing soon
which scaling?
time.deltaTime ...
yes thats unnecesary
altho** in his case.. since he's +=
i do that too still its not necessary
but either way... just something to remember.. mouse delta's work all on their own
with any reasonable code
It's not just that it's unnecessary, it's problematic
It makes your mouse FPS dependent again
i mean i dont see any problem with this whats going wrong?
lol... good stuff
plus u then need to use tiny values..
i dont like
well the camera just isn't moving when I move the mouse, which is obvs what I want it to do
what type of camera movement u working on?
i missed that part
u want 3rd person pov or fps?
Can anyone suggest me a unity c# free course that is useful?
I watched a lot of them but they just write cods fast and the only thing that you can do is copying them, afterward you will learn nothing and cant even write a single line of code by your own.
pov i think? like GTA's camera and movement style
there are beginner c# courses pinned in this channel, and the junior programmer pathway on the unity !learn site is a good next step after learning the absolute basics
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
public Transform lookAt; what is this?
GTA's camera is OTS (over the shoulder) for the most part
if ur doing first person then a setup like this is usually the simplest
ahh okay.. Cinemachine ๐ซ
see i told u cinemachine is the easiest for these cases
needs much less script as well
mmhmm definitely for OTS or Third Person
i wouldnt even attempt a ThirdPerson camera script w/o cinemachine
mainly b/c of camera clipping/collisions
Thanks
i mean its doable definitely but too much work especially since ur just getting into unity
It's not to hard to implement camera collisions in 3rd person
this is what a cinemachine third person setup would look
each ring being an orbit
and it'll shift between them
although cinemachine makes it a lot easier
like 10x easier
public class SkillConnectionComponent : MonoBehaviour
{
public Skill SkillA; // The first skill this connector is connected to
public Skill SkillB; // The second skill this connector is connected to
private void Update()
{
// Ensure that both SkillA and SkillB are not null
if (SkillA != null && SkillB != null)
{
// Always check if both skills are visible
bool bothVisible = SkillA.visible && SkillB.visible;
// Log for debugging purposes
Debug.Log($"SkillA visible: {SkillA.visible}, SkillB visible: {SkillB.visible}, BothVisible: {bothVisible}");
// Set the connector's visibility based on the visibility of both skills
gameObject.SetActive(bothVisible);
}
else
{
// If one or both skills are null, the connector shouldn't be visible
gameObject.SetActive(false);
}
}
}
any idea why update is not being called repeatedly? this script is attached to a prefab which is instantiated when the game starts
In this tutorial, learn how to use Cinemachine in Unity for creating Orbital and free look camera in your 3D game projects, with step-by-step instructions and practical tips to enhance your game development skills.
Cinemachine basics tutorial: https://youtu.be/nWGfDsWu5Yc?si=ss5VJrg3RZ-sauGB
-----------------------------------------------------...
heres a video.. he even uses a car and mentions GTA
might be something helpful
update is definitely called each frame
the debugs are only being run once in my console
Do you have "Collapse" enabled in the console?
they're probably collapsed
did u check if they were collapsed?
I think they might be collapsed
ya
at the far right it'll tell how many of that same error is logged
oh crap you might be right hold on my pc just turned off
usually 999+ in update
Place a log inside the else block
same thing
{
Debug.Log("elsetest");
// If one or both skills are null, the connector shouldn't be visible
gameObject.SetActive(false);
}
gameObject.SetActive(bothVisible);```
since bothVisible is false, you are deactivating the object
once you deactivate it, Update will stop running.
disable the Renderer
don't Deactivate the whole GameObject
would this line work?
gameObject.GetComponent<Renderer>().enabled = false;
myRenderer.enabled = true/false;
get a reference to it in all the normal ways to get references.
using UnityEngine;
public class SkillConnectionComponent : MonoBehaviour
{
public Skill SkillA; // The first skill this connector is connected to
public Skill SkillB; // The second skill this connector is connected to
private Renderer myRenderer; // Reference to the Renderer component
private void Awake()
{
// Get the Renderer component attached to this GameObject
myRenderer = GetComponent<Renderer>();
}
private void Update()
{
// Ensure that both SkillA and SkillB are not null
if (SkillA != null && SkillB != null)
{
// Always check if both skills are visible
bool bothVisible = SkillA.visible && SkillB.visible;
// Log for debugging purposes
Debug.Log($"SkillA visible: {SkillA.visible}, SkillB visible: {SkillB.visible}, BothVisible: {bothVisible}");
// Set the connector's visibility based on the visibility of both skills
myRenderer.enabled = bothVisible;
}
else
{
Debug.Log("One or both skills are null, hiding connector.");
// If one or both skills are null, the connector shouldn't be visible
myRenderer.enabled = false;
}
}
}
ok so i have this working but the connectors are visible even though bothVisible = false
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraMove : MonoBehaviour
{
private const float YMin = -50.0f;
private const float YMax = 50.0f;
public Transform lookAt;
public Transform Player;
public float distance = 10.0f;
private float currentX = 0.0f;
private float currentY = 0.0f;
public float sensivity = 4.0f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void LateUpdate()
{
currentX += Input.GetAxis("Mouse X") * sensivity * Time.deltaTime;
currentY += Input.GetAxis("Mouse Y") * sensivity * Time.deltaTime;
currentY = Mathf.Clamp(currentY, YMin, YMax);
Vector3 Direction = new Vector3(0, 0, -distance);
Quaternion rotation = Quaternion.Euler(currentY, currentX, 0);
transform.position = lookAt.position + rotation * Direction;
transform.LookAt(lookAt.position);
}
}
Something is wrong here coz the camera isn't moving at all when I move my mouse, at this time I was not to use cinemachine, could someone pls take a look at this script and elaborate to me why it own't work and how to fix it please.
what is this Tranform lookAt?
what are u looking at?
transform.position = lookAt.position + rotation * Direction;
transform.LookAt(lookAt.position);``` its a bit weird that you set the things position to and *then* look at it?
idk if im reading that right
wouldnt it be like
Vector3 positionToLookAt;
positionToLookAt = lookAt.position + rotation * Direction;
transform.LookAt(positionToLookAt);```
the character
if lookAt is player's tranform then ofc camera doesnt follow mouse
oh?
if ur contsantly looking at character how will the camera aim anywhwere else?
the position for the camera to aim at should be out in front of the character no?
thats a good point, so I need it to follow the cursor and then have the character do the same
u need to raycast into the world.. from teh camera -> thru the cursor
yes u need to set the character's orientation acoording cursor
ok umm how do i do that
can help visualize it
lol
dude all this would be like a piece of cake with cinemachine u sure u dont wanna use it?
well yall keep pointing me to it but not explaining what exactly it is, so atm no not really. I have the main cam set to the angle I want, and it's attached to the character's mesh
all u woud need to do is set up a empty object to where u want the camera to be and tell the camera to follow that and clamp the rotation
make sure all ur variables are assigned too.. like Player and lookAt
public Transform lookAt;
public Transform Player;```
you would be getting errors if they're not assigned.. but lots of newer guys dont even check their console for errors
could this have to do with the fact this uses an image to visualize it and not a sprite
he is using them they are not unused references so pretty sure the porject wont even work if then werent assigned
it's not assigned atm ik of that because i'm tryna assign it to something to make it move
tbf the camera already follows the player, so I just need to make the camera move with the mouse and have the character follow that point
okay change the last line to
transform.LookAt(new Vector3(-currentY,currentX,0));
and remove the Time.deltaTime from mouse inputs
oh wait
ur using look at
wait
ok i'll wait ๐
try this
ok
i dont use the lookAt method much while using regular cam so i am not that used to it
aha I massively appriciate your kind help regardless
does it work or no?
well I've changed the line, what do I tell look at to well look at now?
did u run the project?
just try running the project after u changed the line