#💻┃code-beginner
1 messages · Page 159 of 1
idk what im doing wrong, but im getting a positive hit even though there cant possibly be anything between the player position and the posChange transform
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Have you tried logging the object you hit instead of just saying that it's not null?
Also, why are you using a position as a direction for your raycast?
because i tried using Vector2.right and Vector2.left and it didnt make a difference so i just tried to do that, which also didnt work
Those would make sense, since they're directions
A position is not a direction, and treating it as such is going to give you odd behavior
Imagine drawing a line from 0,0,0 to the position of poschange, then grabbing that whole line and scooching it so the start point is on top of player. That's what you're checking
That doesn't really make a lot of sense
how would i be able to get a direction between those 2 points then?
hey guys, I wanna add a cooldown for an attack in my game, should I use delta.Time, a corroutine?? any ideas?
Actually that thumbnail is pretty much all you need honestly
omg a video just to say
direction = target - origin
Like I said, the thumbnail basically covers it
i just debug logged the tag of the collider, turns out, the raycast collides with the player its a child of. so i guess instead of "if (hit.collider != null)" i do "if(hit.collider != hit.collider.CompareTag("player") || hit.collider != null )" ?
Probably, but also it'd help to make sure your Raycast is going the right direction
best check null first
Also that
Also probably use a LayerMask so you aren't just hitting yourself
that's the fun part
📃 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 i get this error whenever my character gets close to the item so gets in contact with the collider the boll registeres and the debug message "Player in range" shows correctly but the another message player not in range shows all the time how can i fix it? if you want some more info let me know heres the code: https://gdl.space/getikunicu.cs thirdpersonmovement is my script so it registeres whenever a gameobject with that script collides
Hello, I'm quite new and I'm having a bit of a problem. I'm making a Top-down 2D game, however I have this problem where my movement is not constant, and sometimes the character accelerates more or goes slower than it should
So, if the overlap strikes any object that does not have a ThirdPersonMovement component, you want to run that second block of code?
obviously you are getting multiple results, some have the controller some dont
Either work. DeltaTime may be slightly more simple if you aren't used to coroutines
okay, thanks
Why are you multiplying your input by speed twice
oh so it registers ground for example?
should i compare the tag? maybe
so if it collides with something that has the tag only?
how can i fix it easly
Didn't notice
You're looping through all objects the sphere overlaps with, then checking if each of those objects has the ThirdPersonMovement component on it or not. That doesn't seem like what you want to do, so what is it you're actually trying to check for
im trying to check if the player ONLY is in the radius so then i can enable the item name and image
im trying to get it to work so i can advance later
So you should probably do a CheckSphere instead of an overlap, and use a layermask so the only thing it looks for is the player
does a layermask ignore that specific layer or only focus on it? and if its the latter, can i use more than one layermask on a raycasthit2d?
A layermask shows which layers are permitted. There is no reason to need to use more than one layer mask just put more layers in the mask
oh yeah had no clue there even is something like a check sphere ima try that and let you know if it works
also, you really don’t want to do this in Update()
no else
only guard clause 😠
he wants a debug log to know the first if evaluated false
either way, this should be handled by OnTriggerEnter
also no if statements are actually needed in his code at all
i tried to work with on trigger enter but i was struggling a lil
so i just decided to go the hard way
but code it myself
to learn stuff
I can't find a way to make it work Why?
Do you get an error in unity or just in the IDE
Seeing the lack of syntax highlighting on the right file, seems like Unity hasn't registered that the class is there
Moving the file somewhere else and back in Unity usually solves it
just in the IDE
Then you probably need to regenerate project files
yeah, but you are checking a physics query many times every frame, which is very expensive. OnTriggerEnter only gets called on the one frame where the trigger happens
what you are doing is probably easily 100x more expensive
Thanks
how can i get it to work with the on trigger enter function then?
couse it would've been 100x times easier too
i could use on trigger exit after
to disable the ui
Do you guys know any way to check if an animation has finished? (I want to uncheck the characterMovement while animation is playing)
updated my code to this. it now detects the hits properly, however the hit.transform.position is not where i d expect it to . instead of setting the position to be right before the collider, it is miles away
good evening I need help please I tried to make a script to make movements for a 2d rpg game but I can't correct myself and I would like to know if someone could correct me which is what don't go please
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class player : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{ public float moveSpeed;
private bool isMoving;
private Vector2 input;
private void Uptade().
{
if (!isMoving)
{
input.x = Input.GetAxisRaw("Horizontal");
input.y = Input.GetAxisRaw("vertical");
if (input != Vector2.zero)
{
var targetPos = transform.positition;
targetPos.x += input.x;
targetPos.y += input.y;
StartCoroutine(Move(targetPos));
}
}
}
}
IEnumerator Move(Vector3 targetPos)
{
isMoving = true;
while (targetPos - transform.position).sqrMagnitude > Mathf.Epsilon)
{
transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);
yield return null;
}
transform.position = targetPos;
IsMoving = false;
}
why not use an Animation Event
your method is outside the class
I see some syntax errors and misspellings
this is the third time you have posted this rubbish. Have you configured your IDE?
yeah not likely this whole script is riddled with erros
its just the attack animation, i want it not to move while attacking, do you think I have to use an animation event anyway?
"Have to" no
Should and is the easiest yes
you can also check the current state from animator and use that in some sort of IEnumerator with a waitwhile / waituntil
Okay, thanks a lot
True, that would probably be as easy
can u help me on pv?
i understand if not just asking 😉
I'm not it's what is an idea it's the first time I've done this I watched a video and I'm sorry to ask again but I'm French and translate each one and very complicated sorry
!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
not idea !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
I have already watched everything I don't understand
Integrated Development Environment
Also called your code editor
Sorry🫤
Which one of these are you using?
look at it again and again until you do understand because without it you cannot get help here
someone a couple days ago made the exact same mistake here lol
uptade
maybe its the same guy
Hello, a simple question. How to handle closing app by X in either OS? Because I handle saving on exit in custom function on clicking proper exit button...
However when I tried OnApplicationExit handling and it does not manage to save stuff in time before the process/threads ends and therefore ends up in a mess.
I don't understand anything about the C# language, that's why I'm asking for help, I've never done anything with it, I just stupidly copied a video but he clicks on launch the game and it doesn't launch for me
Must've missed than in my google research, thanks
sounds like you need to learn your c# first before touching Unity then
Working on Win/macOS tho? Not just phones?
its actually the other way around if you read it
this is not about C# this is about preparing your coding environment correctyl, do that first
Important: The return has no effect on iOS or iPadOS. Application can not prevent termination under iOS or iPadOS.
ok but how to do it on the links it talks about line of code and debugging
seems ios limitation only 🤷♂️
!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
ah, so you can't prevent ios from preventing terminating your program or something?
At no point do these guides have you writing code
in that case you may want to save concurrently throughout
this for me?
Well yeah, I am autosaving automatically, but also wanted to save something on exit
Which one should I go to?
for mobile you should use Pause not Exit
Whichever IDE you are using
Sorry i am french i dont good understand
what is the ide 😭😭
what program are you using to edit your code?
the thing you write code in
oh yes in Microsoft Visual Studio
sorry, its me again how can I wait until an animation stops to continue my characters movement
so that is what you click
because is a corroutine necessary
Use an animation event to re-enable movement
only if you don't want to use animation event
I looked at it and it tells me how to configure it and how to update it but all of it I have already done where it blocks it is when Try to launch the game on unity
coroutine is still pretty simple to do
Animator anim;
IEnumerator WaitAnim()
{
anim.SetTrigger("Attack");
//or anim.SetBool("Attacking", true);
var animPlaying = anim.GetCurrentAnimatorStateInfo(0).IsName("AttackAnimation");
yield return new WaitWhile(() => animPlaying);
//do something else after attack
//anim.SetBool("Attacking", false)
}```
If you had configured it, you would have red underlines in the code where your errors are. Do you?
so, i logged the hit.transform. position.x and its 0, it shouldnt tho. why is that?
https://hastebin.com/share/uwonodufeb.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Okay, thanks
thanks!
post a screenshot of your code editor
okay
It is possible that they just installed the Visual Studio Editor package, but it's not able to start working because of the outstanding compile errors.
You're logging player.transform.position.x, not hit.
that's a fun x-factor
And if it's logging 0, then it's 0
so you have NOT done it
im logging both
this should say assembly
but i figured it out. i use hit.point.x and it works
You should probably put some sort of label in there and see which one is which
I'm not that's what I forgot
@hexed granite
https://learn.microsoft.com/fr-fr/visualstudio/gamedev/unity/get-started/getting-started-with-visual-studio-tools-for-unity?pivots=windows#install-unity-support-for-visual-studio
In french
Thanks i see
I follow the tutorial and I'll tell you what it gives, thank you very much
Heya, so just curious about Time.deltaTime. In this code piece should i time the staminaDrain with Time.deltaTime?
{
playerStamina -= staminaDrain;
playerStamina = Mathf.Round(playerStamina);
staminaSlider.value = playerStamina;
movementSpeed = sprintSpeed;
}```
My taught process was that the stamina should be framerate independent, but when using Time.deltaTime the stamina doesn't decrease
if a higher framerate is running that code.. their stamina is gonna drop much faster
lol
You're rounding the value. Unless deltaTime is a whole number it's not gonna do anything
post another screenshot of your code editor when you are done
Mathf.Round here is a bad idea. And yes you should be using deltaTime
I like to bring up that one of the Dark Souls games tied weapon durability to framerate so those with expensive monitors at the same ran into situations where smacking a sword at a wall instantly broke it,
staminaDrain is measured in units of stamina per second. Multiply it by deltaTime to figure out how much stamina to subtract in this frame.
Ah that makes sense yeah, I was already thinking that I should use deltaTime here. Rounding up isn't that necessary I guess?
then the round.. not sure about it
Why are you rounding?
If you want to display a nice whole number, do that when you display the number.
Okay
If anything, you can round before you use the value. Don't round what's stored.
That makes more sense
did you read the warning message
What's the IDE say
I saw a general rule of using deltaTime is whenever you move an object. But from what I've seen and read it's more where you indeed want it to be frame rate independent. So I assume that if you were to shoot a gun you would want to * it with deltaTime too so someone doesn't shoot faster with a better pc, am I correct?
exactly what it says. You are using the wrong method signature. Specifically you have Collider instead of the correct Collision parameter.
well did you look at the correct signature then ?
Check the docs for the function
I would not describe it like this.
look up the correct OnCollisionEnter()
You should think about it from a units perspective.
i dont know how to use the OncollisionEnter function so im kinda confused
Consider "what is the correct signature?"
it doesn't use a "collider"
Google Unity On Collision Enter
a general rule of using deltaTime is whenever you move an object
This would be incorrect. It has to do with converting per-frame quantities to per-second.
im tryna make a gun for a first person game but when i look up and down the gun model just goes further out and if i move my camera to the center its good again is this a feature or am i stupid https://gdl.space/uhipisivus.cpp
I have to say a lot of information about what to use deltaTime is very inconsistent, but the goal is to keep the collisional / physics related logic seperate from the visual logic.
bad scales i would guess
sounds like you parented the gun to a non-uniformly scaled parent object
so what should go instead the "collision" word
input is wrongly using time.deltaTime
did u even click the link ^ ?
spoiler alert: no
yes and im confused the same as i ware earlier
I understand, so as I said if I were to make a pistol that shoots a projectile. You'd want to * the force its going to as someone with a faster PC would shoot faster, correct?
BUT.. with a different ( )
Or maybe but overwhelmed (maaaybe 😅)
thats because you lack c# basics and dont even know what to look for, example what is a method signature?
no, this is wrong: you would use an instantaneous impulse
which is time-independent
let me type something out here...
public class ExampleClass : MonoBehaviour
{
public Transform explosionPrefab;
void OnCollisionEnter(Collision collision)
{
ContactPoint contact = collision.contacts[0];
Quaternion rotation = Quaternion.FromToRotation(Vector3.up, contact.normal);
Vector3 position = contact.point;
Instantiate(explosionPrefab, position, rotation);
Destroy(gameObject);
}
}```
here is the function on the page.. that u said u looked at.
deltaTime
true the terms are esp confusing prob
||Colliders are not Collisions||
but they need to understand why the signature is important
look at ur void method.. and look at the correct one. and see whts different..
ya, after they discover Spot the difference then it can be elaborated on
As shown by the link, the callback function used by Unity requires a signature with the type Collision as the parameter but your using Collider instead - Collider would be valid for On Trigger Enter but not On Collision Enter where we'd care about a bit more than just the other colliding object.
especially when unity auto-calls those methods
the signature? isn't it a method as well?
lol, the way a method is declared is called it's signature
this goes over signatures ^
well not really..
"The signature is the combination of the methods name and its parameter list"
and the return type
ahh yes AND the return type..
can somone help me to start my journey on game dev... what to learn first how to make game egine and after that game development?... i know cpp... what to learn first
wait a minute
i dont lack c# basic
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
this java source is telling otherwise
yes you do, believe you me
when it comes to programming and stuff
C# includes the return type.
well just straight up.. ur method ur trying to call returns a Collision
same but if you learned c# then the errors are universal
the method u wrote. and why its an error.. u have it trying to return a Collider
I've found that people become more aware about the terminology "signature" when attempting to overload but assume that the return type is a part of a functions signature - it's not.
If they did not really know the definition of signature before, they'd know it thereafter.
Methods are declared in a class, struct, or interface by specifying the access level such as public or private, optional modifiers such as abstract or sealed, the return value, the name of the method, and any method parameters. These parts together are the signature of the method.
you'll have to take it up with Microsoft if you disagree in the context of C#
some of unity's methods do return a collider.. but not OnCollision
this has nothing to do with returning anything. the method had the wrong parameters.
Regardless, you'll pick it up now or after several more incidents with it 👍
sorry i was getting confused.. i always think of that as returning a Collision you can then access within the code...
but its not. b/c the void is the return type
it receives a Collision object.
no
an out parameter passes a variable by reference to the called function and demands that something be assigned to it.
ohh okay.. hang on im writting some of this down in a notepad doc
thanks for wording it that way.. that makes sense to me now
i think i found a decent source https://imran-momin.medium.com/defining-methods-unity-c-19feeefbf8fa
In the previous article, we briefly touched on the role methods play in our programs; namely, that they store and execute instructions…
ohh okay, so they are Arguments when Calling a function, and the arguments are wats used for the Parameters of the method beign called
yes
phew..
arguments are what you actually pass in
parameters are what the funciton declares that it wants
yea, okay i think i got those two.
Passed with arguments
Defined with parameters
This probably varies from language to language
alright.. so im solid on those.. its the outs, refs, and the receiving part i still need to freshing up on
special modifiers with the type
i get the receiving part like this functions brings in this variable to use within the body..
and dont get started on params
i can just work around that.. but refs and outs. always kinda confuse me still
ref is the most general form. It allows you to share a variable with the function.
in is like ref but is read-only, and out is like ref but write-only
(and also demands assignment)
@rich adder Thanks for giving again the idea of Game States I was able to fix my problem and handle game flow properly. It is just like I see more organised way to handle game states rather than having bools everywhere and when something strange occurs to not know what you have to change in your bool values.
ohh okay.. so i guess ref is shorthand for reference
There are some other intricacies. For example, in allows you to pass non-lvalues (things you can't assign to, like a literal number)
hence ref readonly showing up in C#12
omg theres an "in" too?!
i doubt ill need that anytime soon 😅
yes. it shows up a lot in ECS code
it's useful if you need to share a large value type with a function
but you don't want it to be allowed to mutate the value type
but aren’t value types not modified when going into a function, without a ref keyword?
Right. Hence in
You want to share, like with ref
But you don't want any modification to happen
exactly after a while so many bools gets difficult to track, much easier to be in a singular state. Once you work events in there like public static event Action<GameState> OnGameStateChanged
Power is unstoppable
what function am i familiar with that uses ref.. Isn't there a MoveTowards or some lerp type function that uses ref
SmoothDamp.
i wanna practice with some of these
It needs to be able to update the velocity argument.
thanks thats it!
also GetRotationAndPosition
that uses out
imma practice these today..
wait there was another one
just realized how bad i am at them
ref is used when the function must be able to read from and write to the reference
would the compiler just know to effectively do the same thing as “in” if it already applies?
All three of the keywords give access to the variable with different constraints. I'm assuming they're all references to the value under the hood (I'd do that with other languages to reduce copying values)
maybe, if it could prove that you never modify the parameter
IDE's are pretty good at that already arent they/
i guess it would make a difference with threads, right?
hence why i get the "Never used" grey variables
Some forms of static analysis are reasonably easy! I did that exact analysis back in grad school..
If you're writing code for others where you don't know what they'll be doing with it, you'll want to consider placing the correct constraints - it's no different from making everything public.
makes sense, what if u didn't and used the wrong constraints.. i could image how much trouble that might cause if someone needs to change one to be accessed in other ways 😐
could be a big ole refactor for sure
that is why we design software not just throw it together
lol.. looks around curiously
id have ALOT of work going from solo to a team
thats all i know
unless i was the Team Lead! "Do as I do!"
(:
Solo dev -> Team lead. A marriage made in hell
If you're just writing for yourself, it's probably fine as long as nobody has to read it (or maintain it in the future) - it's not good practice though (my ocd kicks up)
why there isnt SetSelectedTower(int) in buttons funtions?
ya, im not gonna pretend im the best coder.. but i try to keep it as legible as possible
its a private function
its not gonna show on that list
alright
Would anyone mind giving me some advice on animations currently calling an idle animation I want to be doing any time I'm not playing another like this:
void Update()
{
if(playerUnit.IsPlayingAttack == false && playerUnit.IsPlayingIdle == false)
{
StartCoroutine(playerUnit.PlayIdleAnimation());
}
}
The problem is as soon as I call my other animations im not actually stopping the idle animation and they're both trying to set sprites at the same time is there a way I can easily manage this?
public IEnumerator PlayIdleAnimation()
{
isPlayingIdle = true;
float frameDuration = 0.0417f;
foreach (Sprite sprite in Capta.Base.IdleSprites)
{
image.sprite = sprite;
yield return new WaitForSeconds(frameDuration);
}
isPlayingIdle = false;
}
This is the current idle function
why are you not using the animation state machine w/ transitions?
couldnt u set those on a bool.. (bool true -> idle) (bool false -> transition to other)
Im not sure what you mean by animation state machine, like Unitys built in animator window?
yes
Idk honestly seemed simpler to just hard code it quickly
if hard coding it would not use coroutines since its a continious thing
like starting coroutines from a update is kinda weird
My bad I just meant do it in code since im not familiar with the animator at all
Sounds like you should store the current coroutine
you can add a Coroutine field and store the return value from StartCoroutine into it
its always a good time to learn.. but yea theres code alterations u can do ^ also
You can then pass it to StopCoroutine to cancel the existing coroutine
or use Update for it, count time, and keep track of the current frame index
I'd add a method whose job is to look for an existing coroutine, kill it, start a new coroutine, and save the resulting Coroutine
call it PlayAnimation
Am I better off carrying on as I am than using animator?
Your idea sounds like a fix Fen
it would be simpler to use the animator in the long run.. esp if u have add any more states/animations (imo)
but i aint gonna say if its better 1 way or the other..
If I use the animator I still have to call it in my scripts right?
yea but you can set parameters
and change those.. the animator just takes over
and does the transitions and stuff on its own
u basically just let teh animator animate.. and u tell it what data to use to figure out how to animate
could always just pull from Any State instead of needing every combo of transitions
I need help with a step it tells me to the Common7/IDE directory then select become.exe where is it? @languid spire
and this too
i havent done one with the anystate node yet
What is the minimal approach to Serializing dictionary in the inspector ?
I'd like not to use any plugins like Odin
i should do that too
What? Where?
jsut use a list of structs that have a key and a value field, then on Awake build a Dictionary with it
the tricky part is I need to inspect this dictionary and its values changing at realtime
the 2
right now I'm doing struct that makes new list every change of value
Hmm you make a compelling argument can I duplicate it and have two of the same running independently if im animating more than once character at once?
same idea then with https://docs.unity3d.com/ScriptReference/ISerializationCallbackReceiver.html
absolutely.. u'd have a seperate reference to a seperate instance of hte same animator
Look like this is what I needed to look into. Thanks!
Got it. Ignore that, just select the correct visual studio from the drop down
Ok thanks for your help ill try it out
just look into it
Okay thanks
Ok will do, although honestly im not planning on having real complex animation trees so im not sure it will make much difference
I'm done send screen ?
'yes
well say u just have 2 animations.. walk and idle.. instead of stopping the walk and starting the idle
you could just set 1 boolean for example.. isWalking = false;
Okay
even with small states it can still be an improvement
😦
WHY?
Haven't we been seeing this code all day?
hes trying to get his editor fixed at this point i assume
yep, still no configured IDE
Its from big GameDevExperiments youtube channel
and he speaks French
Sorry 😭
lmao, dont apologize for ur nationallity 👀
Oh ok now I see the value
Why
It's required to get help here
VSCode is always more difficult to get set up than VSCommunity
he said he was using VS not VSCode
why is it so hard in the tutorial it's simple
ohh than not sure why? VSCommunity is usually really easy to set up
screenshot Unity Preferences->External tools
Really ?
yes, really
Visual Guide ^
see if that helps u understand what u missed
I'm not much away from abandoning everything even though I've already done everything
not the attitude that will garner much help tbh
Step 1 Uninstall Visual Studio
Step 2. Reinstall Through the Unity Hub
most straight forward way I've seen it done..
#854851968446365696 @hexed granite
in the video what he shows at 1 minute I don't
I never ask for someone to do it to me, I want someone to tell me where it's going wrong, but given that I'm French, I have no problem
I need your ideas.
I need to find a method, I have a point/crosshair in the center of the canvas, I want to detect when the point is aimed at an enemy/block/etc.
use a raycast
The problem is that it passes through a wall and I don't know how I am going to prevent it from passing through
you need to install the Unity Game Development Kit, after that you can restart and u should be able to select in as Unity as your IDE in the Project Settings > External Tools
Layermask
Use a layermask
The intellisense will highlight everything that's invalid or strange. It'll save you and the people helping you a lot of headache. If you get stuck after the ide is properly setup, folks will help point you to your solution. No one said anyone was doing it for you but the server rule states that we need to get people to properly configure their ide first before doing anything else.
Yea, everyones actually just trying to help.. B/c once you have it set up It will help you a lot
ctrl + Z to undo
may have to remake it then
Can you show the console window?
you only have (1) clip so far.. shouldnt be too hard to remake it
but ive never seen that error
This looks like a runtime error and not the something that you're showing us.
You have an Animator component that is being referenced.
At some point, you are destroying the Animator component.
Any scripts trying to reference the Animator component no longer can, because it has been destroyed.
An error occurs.
You need to prevent the Animator component from being destroyed.```
unity forums thinks it may be that ur destroying an animator
If you double click the error, does it take you anywhere?
but yea im on the fence.. if it were me i'd save what i got and restart
if its still there.. then id look into it a bit more
unless u know that ur destroying an animator somewhere and not telling us about it
this doesnt look like a "Controller"
it looks like u put an animation Clip
where an animator is supposed to go
i havent ureferenced animation in scripts
read my last post ^
oh wait
thats not it.. just testing and that is what it looks like if u Animated a GameObject
@scarlet hull ^ yea ignore that last post.. i thought they may be it but it looks the same on my project
alr
do u have any other animators in the scene?
besides the one on "GameObject"
i have 2 on it
ohhh
not on any other game objects
I'm guessing that the object was destroyed but they're still trying to access it
(code is likely necessary to solve this issue)
Hi guys!! Quick question! I was following a Code Monkey tutorial when I got stuck into an error that probably the solutions is right in front of me. Basically I was implementing the asset "Input Actions" manually like he does on the video, then my C# code does not recognize the class "PlayerInputActions" could you help me? The video is Learn Unity Beginner/Intermediate 2023 (FREE COMPLETE Course - Unity Tutorial) - Code Monkey || Time of the video: 10:45:00
MY GAMEINPUT CODE:
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class GameInput : MonoBehaviour
{
private PlayerInputActions playerInputActions
private void Awake()
{
playerInputActions = new PlayerInputActions();
playerInputActions.Player.Enable();
}
public Vector2 GetMovementVectorNormalized()
{
Vector2 inputVector = new Vector2(0,0);
if(Input.GetKey(KeyCode.W))
{
inputVector.y = +1;
}
if(Input.GetKey(KeyCode.S))
{
inputVector.y = -1;
}
if(Input.GetKey(KeyCode.A))
{
inputVector.x = -1;
}
if(Input.GetKey(KeyCode.D))
{
inputVector.x = +1;
}
inputVector = inputVector.normalized;
return inputVector;
}
}
yea, im lost
any clues? do u think he destroys one?
PlayerInputActions is the generated C# script from your input actions asset
Make sure you used the same name for your input asset
and that you have it generating the C# class
(and that you set it up in the first place)
like this
Hey, I have this jumpSliding method that, well will allow th player to jump slide. The problem I have is that one of the if statments (the very first if statment), is being called repeatatly and then stopes, wehn it is only supposed to be called once and wait till it does it again. Here is the code:
if (allowJumpSliding && Input.GetKey(KeyCode.S)){
Debug.Log("dasdsadsadsa");
rb.velocityX += direction * horizontalSpeedToJumpSlide;
slide(direction);
}
else if (bottomCollider.IsTouchingLayers() == true && Input.GetKey(KeyCode.S) && Math.Abs(rb.velocityY) > verticleSpeedLimitToAllowJumpSlide && allowJumpSliding == false){
allowJumpSliding = true;
Invoke("setJumpSlidingToFalse", jumpSlidingTimeLimitValue);
}```
How do I fix this issue?
If you mean to change out the animator, then you need to reassign it when the one it references is destroyed.```
the other error on the forums seems to think that one gets destroyed. but the reference is still there..
i accedentally
Did you setup the input action?
so its causing an error
those are Animation Clips, not animators
I'll check that again
yes
If you've skipped some steps, it'll not work.
lemme ttry
you need to show the name of the asset
and the settings of it in the inspector
you cut off too much in this screenshot
@scarlet hull it wont even let me delete my base layer
i fixedd itt
Likely they've called destroy on the object with the component but are still doing stuff with it.
looks fine
so what error are you getting?
And where did you put your code?
i think they somehow deleted the base layer of an animator.. by having a 2nd animator?
thats what he said caused the error.. and i can't seem to delete mine.. i get a catch
maybe his editor didn't stop him?
"The type or namespace name 'PlayerInputActions' could not be found (are you missing a using directive or an assembly reference?)",
Likely not, just a missing reference error
Where did you put your script?
well they "fixed it"
I don't have the right one, that's why I think but I can't go back to it
guess we'll never know.. like a tootsie pop
hey can someone help me here? #💻┃code-beginner message
not where did you attach it. I mean where is the script itself?
What folder is it in?
Also I thought it was the GameInput script
not the Player script
Folder Script
where is the GameInput script file itself?
ok and what else is in there? Can you show that folder?
GetKeyDown
the if condition is going to run how-ever mayn times u call the function thats wrapped around it
if u only want the if statement to run once.. ur gonna have to probably set a flag
where's your console window?
guess we'll never know.. like a tootsie pop
or yea GetKeyDown (registers on just the frame its pushed)
so swapping that out may be sufficient
ok so this is just a problem with your IDE
not with Unity/the code itself
regenerate project files I guess?
How do I do that
Preferences -> External Tools
oh yea you were right
a flag, whats that?
boolean variable
it just means like a boolean or something.. like
if(running && canRun)
//do ur stuff
canRun = false;}
so at teh end of the first loop thru u set a boolean to say.. dont try again
lmao
I just had to put vscode there again
idk why it's always putting vs2022 insted of vscode
Thanks
^ yea its easy.. lol i really feel bad when someone can't get theirs set correctly..
maybe its listing them by Superiority 😉
Praetor is the real MVP
List<List<int>> roomMatrix =
{
{0, 0, 0},
{0, 0, 0},
{0, 0, 0}
};
why is visual studio not liking this
im trying to make a list of a list of ints
yea 😄 someone smarter has to chime in
That syntax can only be used with arrays. You can do this instead:
List<List<int>> roomMatrix = new()
{
new() {0, 0, 0},
new() {0, 0, 0},
new() {0, 0, 0}
};
Nevermind
OnTriggerEnter doesn't work for me
is the thing itself supposed to be set to is trigger?
or is the thing it's colliding with supposed to be set to is trigger?
The Three Commandments of OnTriggerEnter:
- Thou Shalt have a 3D Collider on each object
- Thou Shalt tick
isTriggeron at least one of them - Thou Shalt have a 3D Rigidbody on at least one of them
thanks you very muches you dear sir
system.badimageformatexception:format not executable (.exe) or library (.dll) is invalid
How do I fix
this is a code channel, that's not code related (also... just google that exact error)
Context?
Where do I ask then ?
Where you asked it last time.. #💻┃unity-talk (crossposting isn't allowed either 😉 )
what type of a raycast should i do when doing third person pickup system i was thinking about a beam but thicker
so like a normal raycast but thicker
should i use a square cast?
You mean box cast?
Why not just do a ray cast?
cuz the way my cinemachine camera works
it would make it very awkward to have a small ray
right now im testing it
and thats how im casting my ray
Look at the different (shape) XXXCast methods and pick the one that best fits your situation . . .
okay thanks 🙂
The image doesn't really show why a raycast wouldn't work, but its neither here nor there.. use ☝️
Whoop whoop, got the first step of my (Drag to drop waypoints) mechanic
dragging = Input.GetMouseButton(0);
objectToTrackMousePosition.SetActive(dragging);
float dist = Mathf.Infinity;
//update mouse position
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray,out hit,dist))
{
lastMousePosition = hit.point;
}
objectToTrackMousePosition.transform.position = lastMousePosition;``` nice and simple so far
now, every x amount of distance (i was debating on distance vs time) it'll drop a waypoint on the position.. then i'll draw the shape
i need to make some states now, i have a camera script that moves the camera around when i click and drag. or maybe a simple bool will do it
if a unit is selected i'll just disable the camera script
@timber tide for some reason, my OnBeforeSerialize gets called whenever I enter play mode. 😦
idk
I just want a method to be called when I'm done making edits in inspector
and I can't make a custom editor script for this without screwing up the ruletile editor
Maybe make your own method that finds all method implementations of InspectorDebug()
hello so i'm getting nullreferenceexception on line 22 (second image) and i do not know what that means or how to fix it can anyone help ?
and make big button that you press
means ur trying to do something with something that isnt assigned..
it knows theres a spellmanager.. but its not assigned.. its null
it means telling it what instance of that script
that ur using
and also.. dont use the exact same name as the name of the class
tried doing so but the ide didn't like it
its gonna get confused if the name and the type are the same name.. as u have spellmanager forboth
well the type has to be exactly the same as the file name..
change the name.. not the type.
spellmanager mySpellManager;
mySpellManager.cast()
actually, I forgot I already have a custom editor lmao
hey guys, I have a question in regards to network RPCs. I've tried to RPC an array of different "gun shot info" structs, however I have received the error message shown below. Is the only way to RPC this information by using a series of individual RPCs for each gun shot info in sequence? many thanks.
i need a way to reference my class inside a function that is inside that class, i tried using the code in the image bellow but unity doesn't like it
yeah..
unless u need a new version of it
either way, the IDE doesn't yell at me. maybe u shouldn't use a var b/c u already know its a spellmanager
spellmanager s = new spellmanager();
i did not know the this thing existed
i can't use it inside a static function tho
ya, b/c a static function can only exist once..
what does that mean ?
if its a static function inside of that class.. and u try to make a (new) one.. you now have (2) static functions ** of the same function **
which u cant do
i'll read that thank you
for(int i = 0; i < roomCount; i++)
{
horizontalChoice = Random.Range(0, 2);
verticalChoice = Random.Range(0, 2);
if (i > 0)
{
while(horizontalChoice != leftCheck || horizontalChoice != rightCheck)
{
horizontalChoice = Random.Range(0, 2);
}
while (verticalChoice != upCheck || verticalChoice != downCheck)
{
verticalChoice = Random.Range(0, 2);
}
}
upCheck = verticalChoice - 1;
downCheck = verticalChoice + 1;
leftCheck = horizontalChoice - 1;
rightCheck = horizontalChoice + 1;
roomMatrix[verticalChoice][horizontalChoice] = 1;
}``` i dont understand how this is giving me an infinite loop
What are leftCheck and rightCheck
integers
Are they the same number
well there being randomly assigned in a very small range so they should reach that number
But there is a possibility they are different numbers, right?
Then I don't know how you think this could end:
while(horizontalChoice != leftCheck || horizontalChoice != rightCheck)
{
horizontalChoice = Random.Range(0, 2);
}
If it's not equal to left check OR its not equal to right check, you loop
If left check and right check are different numbers, it is impossible to be equal to both to get out of this loop
yeah and each time im changing its values which could make it the same as left or right
no its not cause its OR not and
And if it's the same as left, it is no longer the same as right, so the loop continues again
oh wait
Let's assume left check is 0, and right check is 1, okay?
no it does need to be and
If horizontalChoice randoms into 1
i was getting them mixed up
it is no longer equal to left check so it loops
Hello , ive wanted to ask how can i make a transition from a 3D-scene to a 2D-scene?
I'm mainly asking because ive had an idea that upon interacting with an Object/NPC , it would trigger an transition from the 3D-Space to 2D-Space to play an An Animated interaction with the object/converstation with the NPC.
this is short visualization of the transition in my mind
look at mario
Paper Mario and Mario Odyssey both did that
in terms of physics, that is going to be rough, because 2D and 3D physics systems are totally different
oh nuts
i am aswell an absolute begginer , i got into unity since last week or so
i just thought making something like this would be fun but no idea where i could start so ee
the original scene becomes still image and rips to reveal 2d game?
yeah something like that
I would start getting the 2 scenes working first then worry about the transition effect later
there is like a transition in a split frame where you do notice of it happening
oh alrighty! ill be getting to it then
You could have the camera output to a render texture, put that texture on a Quad that has this tearing-in-half animation, and behind it have your new scene. When you need to change scenes, you have the active camera take a snapshot and then additively load the 2D scene, drop in the animated ripping quad, and then quietly unload the original scene. Actually a pretty involved system, but it'll make for a cool effect.
Things to learn:
- How to output a camera to a render texture
- Spawning an object with the render texture as it's material's main map
- Asynchronous scene loading, including having a "transition scene" (that is normally used for a loading screen)
But definitely work on getting the scenes on either end working first before you make the transition effect. It won't do much good unless there's stuff to load on either end
alrighty!
actually when i think about it , it doesnt have to be a 2d scene
I could pull it off by making it look 2d within the 3d space by changing the cameras and having the animation scene out of players view
and i bet it would be an easier time
and even better i could mix both 3d and 2d objects withing the same space giving me more stuff to mess around
ive been trying to wrestle with this for a while so any thoughts on the matter would be appreciated i know its probably not the best method of going about it but i wanna try and finish it``` public List<List<int>> roomMatrix = new List<List<int>>
{
new List<int> {-1, -1, -1},
new List<int> {-1, -1, -1},
new List<int> {-1, -1, -1}
};
public List<List<bool>> roomsVisited = new List<List<bool>>
{
new List<bool> {false, false, false},
new List<bool> {false, false, false},
new List<bool> {false, false, false}
};
// Start is called before the first frame update
void Start()
{
roomCount = Random.Range(3, 6);
for(int i = 0; i < roomCount; i++)
{
horizontalChoice = Random.Range(0, 2);
verticalChoice = Random.Range(0, 2);
if (i > 0)
{
while (roomsVisited[verticalChoice][horizontalChoice] == true)
{
while (horizontalChoice != leftCheck && horizontalChoice != rightCheck)
{
horizontalChoice = Random.Range(0, 2);
}
while (verticalChoice != upCheck && verticalChoice != downCheck)
{
verticalChoice = Random.Range(0, 2);
}
}
}
upCheck = verticalChoice - 1;
downCheck = verticalChoice + 1;
leftCheck = horizontalChoice - 1;
rightCheck = horizontalChoice + 1;
roomsVisited[verticalChoice][horizontalChoice] = false;
roomMatrix[verticalChoice][horizontalChoice] = i;
}``` im trying to make a loop that will choose a starting point in my list of lists of ints and lable that 0 then choose an adjacent point (either above or below or left and right) then lable that 1 and so on until i reach the required amount without going back on myself
What are leftCheck, rightCheck, upCheck, and downCheck? If any of them are 0 or 1, these loops cannot end
there integers that get updated based on what the random choice is here upCheck = verticalChoice - 1; downCheck = verticalChoice + 1; leftCheck = horizontalChoice - 1; rightCheck = horizontalChoice + 1;
What do they start at
there not assigned at start
well no cause they get updated before the loops even happen
Oh, there's an i > 0 check there
So, let's think this through. They're at 0 to start. Let's just focus on horizontalChoice and leftCheck and rightCheck
right ok
If horizontalChoice randoms into 0, then leftCheck becomes -1 and rightCheck becomes 1.
If horizontalChoice randoms into 1, then leftCheck becomes 0 and rightCheck becomes 2.
Actually, hang on, are you still getting an infinite loop or is your issue that it's not doing anything
because that outer while loop should never run. At no point are you ever setting any value in roomsVisited to true
no im not getting an infinite loop
roomsVisited[verticalChoice][horizontalChoice] = false; omg im setting it to false
ugh
ok so now it sometimes works perfectly
and sometimes goes into an infinite loop
You should probably learn how to use the debugger so you can step through the logic
You have a situation where you have no possible choices that result in a roomsVisited of false
Try reinstalling the package
wdym sorry?
You have hit a situation where roomsVisited[0][0], [0][1], [1][0], and [1][1] are true and those are the only possible values you can get
so it's always true
Hi guys, I have two scenes loaded at the same time with LoadSceneMode.Additive, each scene has a camera in it but i want each camera to only see the things in its respective scene, right now everything is visible at the same time to all cameras. How can I fix this? I am very new to unity
got it thanks 
but then shoudnt it look at [0][2] or [1][2] or [2][0] as there adjacent
how
horizontalChoice and verticalChoice can literally only be 0 or 1
how
Because int Random.Range is max eclusive
ohhh right
so i need to change them all to 3 then
am I allowed to ask my question in more than one channel if it's an appropriate channel
its still running infinitely tho
So, once again, learn to use the debugger and step through it to find out what situation is going infinite
you are in a position where all possible values for your roomsVisited are true
ok i got it working with the debugger
so its not infinite looping now
however on odd occurances the path is not adjacent tiles
i think the issue is
is that technically say my starting point is [1][1]
that means vertically [0] is valid and horizontally [2] is valid making the next point [0][2] which is not adjacent
but i wouldnt know how to fix that
What are some ideas to keep a large script with numerous members clean from your header space? I've been just cramming them all into structs even though I'm not exactly passing them anywhere. A lot of my methods act directly on the member variables without parameters for the sake of simplicity. Only problem I dislike is it does create more line space as I've gotta use another dot operation to access it all.
As much as I may dislike setting up header files, it does keep your scripts pretty shiny
what do you mean by header files?
like its not C
if you are just talking about all your fields and stuff and keeping it organized
i tend to try to not have 1 class handle too many different things, and when i need it to i will just keep fields used by sets of methods close to those methods and use regions to group
@timber tide I solved it. I just made a custom editor, where I only defined an override for OnInspectorGUI, to call a public method. It still calls way too many times, but at least it only calls when I’m editing it.
would anyone be willing to kind of "teach me unity" and how to get started with c# for unity on a 1 on 1? i have slight knowledge of c++ if that helps any
Ah, I forgot about regions. That's probably something I should consider using more
Also nothing wrong with just using composition, can just have a few other objects in your thing for handle different features of it
If lines start getting long a few getter props can handle that
there is too much to learn for a voluntary 1 on 1 apprenticeship. You’ll need to travel around and learn
orange is the selected camera
why does one of the cameras not have a small icon above it
I cache all my values
when you think of modifiers from like hundreds of items, it's hard to just get item stats each time you do like an attack
Im quite doing that, just updating parameters at certain times
but im quite doing the hardcoded for everything
like if i got a double damage buff, i update recalculate the strength fully
namespace Stats
{
public enum StatValueType
{
Flat = 0,
PercentAccumulate = 100,
PercentMulti = 200,
}
[Serializable]
public abstract class StatValue<T> where T : Enum
{
public StatValue(T statType, StatValueType valueModType, float value)
{
StatType = statType;
StatValueType = valueModType;
Value = value;
}
[field: SerializeField] public T StatType { get; private set; }
[field: SerializeField] public StatValueType StatValueType { get; private set; }
[field: SerializeField] public float Value { get; private set; }
}
}```
I stick to mostly a flat, percent accumlative, and multi for the majority of formulations
that's neat
so like it's smart to autodecide how it handle the stat update
rather than you manually handling how you plug in the extra buff you add
mods are like blocks where you shove one in and recalculate on one specific method
Well, you'd normally have:
- some base value
- some stacking multipliers
- some non-stacking multipliers
- some constants
etc
i love the fact that a lot of rpg did this very nicely
i tended to just implement buffs and debuffs as just a stack of objects, that all have various methods for the stats they effect that each accept and return a value to modify
Yeah, just loop through them and evaluate then later combine - possibly many different stacks as well.
buffs have been tricky to implement because snapshotting stat references is a pain (think of abilities still lingering on the scene)
I'm not sure how I want to handle that
im having trouble making my bullet damage the player because when i hit the enemy it takes damage but when i get rid of all its helth there in an error Destroying assets is not permitted to avoid data loss. If you really want to remove an asset use DestroyImmediate (theObject, true); UnityEngine.Object:Destroy (UnityEngine.Object) Enemy:TakeDamage (int) (at Assets/Scripts/Enemy.cs:19) Bullet:OnTriggerEnter2D (UnityEngine.Collider2D) (at Assets/Scripts/Bullet.cs:20)
and also even though i have in my start function health = 100 it doesnt update and i just has negitive health
The error said you're trying to destroy an asset.
Likely you're referencing an asset instead of an instance in the scene.
are you trying to destroy the prefab itself?
https://gdl.space/iyisefahip.cs My old buff system, trying to do something better
yes
well something like this basically is wrong
public GameObject myPrefab;
void Method()
{
Destroy(myPrefab);
}```
but now im just trying to redo my main parameter handling
how? im new to unity 🥲
Replace enemy.TakeDamage(20) inside the physics callback function with other.GetComponent<Enemy>().TakeDamage(20)
Likely your referenced enemy was the prefab and not the enemy in the scene
oh nvm you got it sorted 🙂
Also, this would imply you've only got one.
The error occurred because you told the prefab to go destroy itself.
omg thank you this worked 😀
that makes sense now lol
Because the referenced enemy was a prefab
i see my mistake lol
i dont understand how i can get an infinite loop sometimes but then it work normally other times
{
new List<int> {-1, -1, -1},
new List<int> {-1, -1, -1},
new List<int> {-1, -1, -1}
};
public List<List<bool>> roomsVisited = new List<List<bool>>
{
new List<bool> {false, false, false},
new List<bool> {false, false, false},
new List<bool> {false, false, false}
};
public List<List<bool>> roomsValid = new List<List<bool>>
{
new List<bool> {false, false, false},
new List<bool> {false, false, false},
new List<bool> {false, false, false}
};
// Start is called before the first frame update```
{
roomCount = Random.Range(3, 7);
for(int i = 0; i < roomCount; i++)
{
horizontalChoice = Random.Range(0, 3);
verticalChoice = Random.Range(0, 3);
if (i > 0)
{
while (true)
{
if (roomsValid[verticalChoice][horizontalChoice] == true && roomsVisited[verticalChoice][horizontalChoice] == false)
{
break;
}
else
{
horizontalChoice = Random.Range(0, 3);
verticalChoice = Random.Range(0, 3);
}
}
}
upCheck = verticalChoice - 1;
downCheck = verticalChoice + 1;
leftCheck = horizontalChoice - 1;
rightCheck = horizontalChoice + 1;
for(int a = 0; a < 3; a++)
{
for (int b = 0; b < 3; b++)
{
roomsValid[a][b] = false;
}
}
if (upCheck > -1)
{
roomsValid[upCheck][horizontalChoice] = true;
}
else if (downCheck < 3)
{
roomsValid[downCheck][horizontalChoice] = true;
}
else if (leftCheck > -1)
{
roomsValid[verticalChoice][leftCheck] = true;
}
else if (rightCheck < 3)
{
roomsValid[verticalChoice][rightCheck] = true;
}
roomsVisited[verticalChoice][horizontalChoice] = true;
roomMatrix[verticalChoice][horizontalChoice] = i;
}```
Get to the infinite loop state and break with the debugger. Then inspect where it is looping and why.
i put in a break point then go in with the debugger and its always like the breakpoint is unable to be hit
so idk what to do
Don't put a breakpoint. Just got the break button
It looks like the pause button and should be on your toolbar at the top.
{
if (roomsValid[verticalChoice][horizontalChoice] == true && roomsVisited[verticalChoice][horizontalChoice] == false)
{
break;
}
else
{
horizontalChoice = Random.Range(0, 3);
verticalChoice = Random.Range(0, 3);
}
}``` its cause its not getting to the break inside the if
but idk why it should
Well, if it doesn't, then the conditions are not satisfied. And you can confirm why that happens by stepping through the code.
roomsValid is always true or roomsVisited is always false. Check the values of the vertical and horizontal choice and the elements inside these arrays. It's really a simple thing to debug.
Combinations can repeat so this could take a while stepping through the code 🥹
Prove that there are always valid choices after i > 0
Just to eventually determine that none were valid and not visited
there are always valid choices
its the adjacent tiles
I'm assuming this is a grid maze generation where there are corner cases with valid rooms that have been previously visited though.
yes it checks if the room going to next is adjacent or valid and if that room is the room we've been to before
So how many times should it try if there are no more valid/non-visited rooms?
You can check that by looking at the array in the debugger.
well at the start of the code it generates how many rooms there will be and after that many rooms are spawned the code will stop
What do you actually see in the debugger?
Unless you've got something prior that escapes if no neighbors are valid/un-visited
i saw that some of the valid rooms werent be turned to true even if they were valid
Then you need to investigate the place where you expect them to be set to valid.
downCheck = verticalChoice + 1;
leftCheck = horizontalChoice - 1;
rightCheck = horizontalChoice + 1;
for(int a = 0; a < 3; a++)
{
for (int b = 0; b < 3; b++)
{
roomsValid[a][b] = false;
}
}
if (upCheck > -1)
{
roomsValid[upCheck][horizontalChoice] = true;
}
else if (downCheck < 3)
{
roomsValid[downCheck][horizontalChoice] = true;
}
else if (leftCheck > -1)
{
roomsValid[verticalChoice][leftCheck] = true;
}
else if (rightCheck < 3)
{
roomsValid[verticalChoice][rightCheck] = true;
}``` which is here but that should work fine
Yeah. Maybe have a condition where after 100 attempts, it enters a section of code with the break point - couldn't imagine how many times he'd have to traverse before getting to the rooms with unwanted behavior.
There is only one true valid room after each iteration
Add an else in the end and put a breakpoint there. It's really simple...
Isolate the condition that causes the issue and break in it. Easy.
Also what ティナsaid.
I'm guessing they're randomly picking rooms though and that the unwanted behavior occurs when no rooms meet the conditions to continue 
what how
You set all the rooms to false there. But only set to true one of them.
oh should they not be else if's
Instead of randomly picking two sets of three numbers an unknown amount of times, maybe add the selectable rooms to a pre allocated list and randomize the order. You could then remove the first element until a valid element was found or escape when no more is available.
Note: to avoid allocation, just have a list with a capacity of 9 and clear it before adding the next set of rooms for testing.
how would i make a trigger teleport an object to that trigger's y position when the object goes into that trigger?
can use OnTriggerEnter or Spherecast an area
Basically, like that. Set the object's Y position to the trigger's Y position in OnTriggerEnter
ok, thanks! 🙂
is this java or c#
From this context alone impossible to tell. it's valid in both languages. Seeing as we're on the Unity server, very good chance it's C#.
does anyone have good documents on raycasting?
thx
Next time you can just use google, it will give you the official Unity docs.
👍
EDIT: FOUND THE ANSWER ... Preferences -> Asset Pipeline -> Auto Refresh -> Enabled
(original problem.. I am not sure if this is the right place but... I just updated project to Unity Version 2022 and I noticed if I save a sprite in paint.net unity will not show the changes anymore until I run the game. Is there a way to see sprite changes even if the game isn't running again?)
Anyone know why my SceneManager.LoadScene() isn't working in a built version of my game?
Pressing the start button works in the unity editor as expected, but once I build the project, that button just not longer works anymore. It seems to affect the buttons with a certain script onclick? as the other buttons work but i have no idea. Anyone have any pointers or possible fixes?
in what way does it not work
does it respond to the mouse at all (tinting etc)? HAve you checked the log files?
putting a Debug.Log in there and seeing if it shows in the logs would be a good start
cant check if it responds to the mouse because i disabled that
i will try a debug log real quick
What i was thinking, but I've never used c# so couldn't tell. Seems like java and c# r really similar though
I have figured out the issue thanks for the response
What was the issue?
basically
i was trying to save data and read data right
and i did that by writing and reading to a txt file
but on the built version, something was different I guess, and an exception was getting thrown whenever I tried to write to the file, because it didn't exist according to unity.
then because of that it didnt run the line under it, which was to load the next scene.
Hello, I am new to unity and new to C#, I am trying to do simple first person movement and so far it was going good with a youtube tutorial using unity's imput system, the problem is that tho the video said it could also be used for 1st person games, the tutorial only focused on third person, and I dont know how to implement the 1st person camera and mouse imput into the script. Everything else works fine (jumping, moving and gravity)
these are immages of my code ^ (sorry for the mess)
and here an image of the imput actions
thank you in advance
Look up a tutorial for a first person controller and switch between the 2 modes.
so redo the whole thing?
cause I tried implementing the camera from a different video into my script and it didnt work
No need to redo everything. Just add the first person logic additionally(maybe even in different script) and switch between them.
Got it thanks
if (Physics.Raycast(Cam.transform.position, Cam.transform.TransformDirection(Vector3.forward), out hit, Range) && hit.transform.tag == "Enemy")
Does anyone know which of each code I can expand the detection area?
Range is the length of the ray. But a ray is infinitely thin, so if you want to expand it outwards you want a different cast type
Like SphereCast
I don't get what I want
Is very deep.🤯
I mean that's fine. It's a common problem in this channel anyway
The "don't get what I want" part
I'm curious about that code but I'll have to see.
It's super embarrassing when something thinks about something else, lol...
That's fine. If you feel like you're not able to convey your thoughts, just use Google translate or something.
yeah : (
why
how to ignore it?
Don't ignore it. Physics.Raycast returns a boolean, act on the boolean and don't read hit if it's false
also, understand the value of stack traces and everything else in the troubleshooting section of that site, so you can see how obnoxious it is to provide an exception without showing the line numbers
but the raycast should only work if it hits an entity
I have a problem, simply when I paste the SphereCast code and it gives me errors, but I don't want to ruin all the codes.
Hello, Everyone. I was curious on what the best methods for saving, accessing, and modifying large amounts of text for a text based game would be. In this case, player makes a choice in the beginning of the game, and later down the line it'll display a certain text if the player chose option A, or a different one if they chose option B, etc. The game will be filled with such choices and differences. From what i found, hard coding it is probably not the best method and i was curious if there was a better way?
you are trying to access the hit variable which is null because the raycast was false, simply put the raycast function on an if statement
there's no errors anymore but it still cant recognize that the object is an entity
How are you defining entity in your code
its just a layer mask
A LayerMask is not a layer https://unity.huh.how/bitmasks
You'll have to use a plain int to represent a single layer
there is actually no point of detecting the layer mask in that if, you can just put a mask on the raycast directly and it will only become true if hits the specified layer
you didnt anchor it
There definitely are reasons, like if you dont want to interact with something through a wall
thats a good point, but checking for a tag would be better in this case
A tag wouldnt do anything here, not really sure what you mean by that.
put a tag on the enemy and compare the tag of the gameobject hit by the raycast
Well yes I understood that part, but theres no difference in checking vs a layer here. I find using both layers and tags for the same purpose is awkward. since you are forced to use layers for physics, it's better to just stick with them
using tags and layers are different.
Also Using tags at all is ugly (working with strings)
I feel they're just talking about the logic being simpler? Not really a good justification for mixing the 2 systems
its basically
if (hit.collider.CompareTag("Enemy") {}
vs
if (hit.gameObject.layer == 3) { }
if(hit.collider.TryGetComponent(out Enemy enemy))
and if you accidentally change the order of a layer that whole thing can break
thats also valid
both are very fragile imo
remembering to put tags on things is a pain
The same can be said about the tags, if you change the string. But its insanely easy to just write one piece of code which stores the values for either. Regardless, you're talking about how the code looks which imo shouldnt even be a factor. You now mix 2 systems and anyone that helps on the project has to wonder what will use a tag and what will use a layer. When you want to use physics stuff for the object as well, are you gonna create a tag and a layer?
The GetComponent code as well works, but layer based is much faster.
personally, i use layers as filters and tags for detection
A raycast has both a filter and is used for detection, again mixing the systems
Or just any physics function in general like overlap or any cast
in that case i use both
¯_(ツ)_/¯
i filter the object hit by the cast with layers, then check whats what with tags
that makes no sense, the tag check relies on the hit from raycast.
Also raycasts are def not expensive lol
oh it doe not make any sense, i missed the using of HIT in the 2nd if.. facepalms hard nevermind me 😐
ill just delete that to be sure :p
allgud just thought I'd point that out lol
yea thank you, quite the blunder and might have caused a lot of confusion 😛
what is this "thinking first" y'all been talkin about? sigh 😛
oh god too many drivers like this i deal with daily 😆
SHAME! 🔔
what do i do with unity, im completely new to coding not even a single time i code before
not my first time i tried Godot before it was easy man
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
There are resources pinned to this channel
playerVelocity.x = Mathf.Sqrt(hit.normal.y * playerSpeed);
I'm basically performing a wall jump
Whenever I press jump I want to jump on the wall's normal direction
But required argument is a float
Is while the normal is a vector
is this how I should be doing it?
Hit normal y would be 0 for a vertical wall.
Wdym by "jump on the wall's normal direction"? If you just want to use the normal as the direction then set your velocity to it * speed.
you mean like this?
jumpVector = hit.normal * speed;
idk why the player just jumps up
lmao It works now
I have this timer which should give me air movement once it reaches 0
but It doesn't seem to happen
full code https://paste.ofcode.org/zqiyecMWszDDBN4LdfLvqc
debug your values, also don't use == on floats
how to adjust animation loop interval?
what should I use?
clip the ending ?
not sure where the code question is
hello someone can help me i dont know i make the state machine for the enemy can someone can help me i need the enemy patrol the area after 5 secons the enemy make the animation of idle and patrol again when he see you chase after the player someone can help me with that?
use an enum and Update and you're pretty much done
or coroutine is easier for timer
how i do that?
you need a script
Hello there everybody, i've a question. I wanted to play the game i created in unity with my friends online. How should i do that? I can host the server on my pc if needed. Just wanted to try the game out with some friends
If you didn't make it multiplayer, it can't just be played multiplayer.
its not that trivial
yep and i have that script but the idle state is only start and i have the walk but only the idle is start
Can i please get some help?
The issue/problem: 'GameObject' does not contain a definition for 'canMove' and no accessible extension method 'canMove' accepting a first argument of type 'GameObject'.
My Code (watch out its a long one):
public GameObject CoilyBoily;
public float speed = 20f;
float xRotation = 0f;
public LayerMask layerMask;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
CoilyBoily = GameObject.GetComponent<CoilyBoily>();
}
void Update()
{
float xAxis = Input.GetAxis("Mouse X") * speed * Time.deltaTime;
float yAxis = Input.GetAxis("Mouse Y") * speed/2f * Time.deltaTime;
xRotation -= yAxis;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
Mathf.Clamp(yAxis, -90, 90);
player.Rotate(0f, xAxis, 0f);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
}
void FixedUpdate()
{
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity, layerMask))
{
CoilyBoily.canMove = false;
}
else
{
CoilyBoily.canMove = true;
}
}```
show script. use links
can i show you images
GameObject doesn't have canMove property init
its a bool on my script
pretty sure you wanted CoilyBoily not GameObject
mm, what am i missing. It's a simple 2d soccer game, what do i need to do in order to make it multiplayer?
You've declared your CoilyBoily variable as type GameObject. You probably want it to be of type CoilyBoily considering that's what you GetComponent<> in your Start function.
correct
so declare it properly
use links from !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.
The entire multiplayer framework. There is no magic button to just add "what you're missing". You need to integrate multiplayer from the very start. Unity has their Netcode for GameObjects you can use.
ok now its
An object reference is required for the non-static field, method, or property 'GameObject.GetComponent<CoilyBoily>()'
@frosty hound https://www.youtube.com/watch?v=stJ4SESQwJQ that's what i'm looking for i think?
Netcode for Unity is an amazing real-time multiplayer solution, which is part of the wider Unity Gaming Services.
Checkout Netcode: https://on.unity.com/3blzOy3
In this video you'll learn:
How to get started with Netcode
The different between server & client authority and when to use each
How to write performant network code
How to use Networ...
personally i use Alteruna
thats the scripts because i dont know how i put links
its free
what editor is that...also what did i say about using link
copy n paste it
its not rocket science
@tepid summit do you have some sort of tutorial to set it up?
That's a start, yes
no dude, click the links in the bot message
alteruna?
yep sir
i can help you
idk
would be great
my error message changed
the error tells you whats wrong
GameObject is the type/ class
gameObject is the property
However, you can just do CoilyBoily = GetComponent<CoilyBoily>();
they just told you..