#💻┃code-beginner
1 messages · Page 276 of 1
How?
GetComponent is very slow. Do it once and reuse the same renderer
it means not calling GetComponent every single frame.. (which is expensive) u should make a variable and call that getcomponenet in start or awake
Either set the entire position at once, or store it in a variable, modify it, and put it back
then u can use the variable
transform.position = new Vector3(transform.position.x, 5f, transform.position.z);
-- how u reckon this would do for ur situation?
Awake is where I put them
But it`s only for test
I don't know why you sent me this
Unity learn
well thats fine then.. but even for tests u should use good code..
Thanks
to get into good habits
All the more reason to cache it so you cut your code in like, a quarter. Why spend so much time retyping stuff for temporary code
And I don't know why you've sent me this
Still not printing
Are you getting any errors anywhere? Even in unrelated code?
yes
yup!
that's a problem
i discovered this during a game jam
one per human being
it took me way too long to work that out
(or really one per set of input devices)
PlayerInput is really designed for local multiplayer
ahh my thoughts go out to you 😬 loll
the name is quite literal (:
game jams be brutal sometimes
I use a PlayerInput component so that I can easily access the correct InputUser, but I get all of my input through InputActionReference
Still not working 🙃
I did used to have a big "input manager" that received messages from the PlayerInput component and called other methods
show your setup now
how many PlayerInput components are there
Once component
How is that? That`s changing y,z
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.E)) GetComponent<Renderer>().material.color = Color.black;
if (Input.GetKeyDown(KeyCode.Space)) GetComponent<Renderer>().material.color = Color.white;
if (Input.GetKeyDown(KeyCode.Tab)) GetComponent<Renderer>().material.color = Color.green; Debug.Log(transform.position);
if (transform.position.y < 5) Debug.Log(transform.position);
if (Input.GetKeyDown(KeyCode.O))
{
transform.position = new Vector3(transform.position.x, 5, transform.position.y);
}
if (Input.GetKeyDown(KeyCode.L))
{
transform.position = new Vector3(transform.position.x, 0, transform.position.y);
}
}
}
you're putting the y into the z part
transform.position = new Vector3(transform.position.x, 5, transform.position.y);
is it a child of anything?
He was at 0
is the parent at -6?
guys it is even possible to set animations for a prefab because it doesn't let me do it
double check that you have no other player input components by searching the hierarchy for t:playerinput
bugs are usually man-made
Just the one
It's normal, probably a bug
how would I set this up properly if (Input.mousePosition <= transform.position)
probably gonna need to convert ur mouse position to world space
I tried to add animations to my prefab and said it won't play, why?
also, is your project actually set to use the new input system? It should have prompted you to switch this when installing the package
so it would need to be in update
ya ofc.. u want to be checking ur mousePosition every frame
it's "Active Input Handling" in the project's Player settings
Both is fine.
The next thing I'd do is to use the Input Debugger window
could someone please answer me
it's in the Analysis category.
well, is the animator controller valid?
the Animator component should have a controller assigned to it
Alright, I'll see that
it shouldn't say "None" or "Missing"
id delete and remake the animator
I am elbow-deep in a rewrite right now and I can't run my game to show you what it should look like
seems broken
When the game is running, the input debugger should be able to show you the currently-enabled action maps and actions
@rocky canyon i believe I did it but still have the error CS0019 Operator '<=' cannot be applied to operands of type 'Vector3' and 'Vector3'
ya u cant compare vector3s like that
it's just entry -> animation
it would be Vector3.x y or z
okay, but is the animator controller assigned to the Animator component?
u should be comparing 1 of hte properties of the vector
I did it tons of time but still not working
the animator controller is an asset
the Animator is a component that references an Animator Controller
yep
Worker[0] errors ususally go away wiht a restart.. but ive never seen one prefixed to an animator error like that so idk
hmm well it got rid of errors but isnt giving me the result i need
theres no clips inside that animator
Apparently it's working
open ur animator and drag ur clip into it and set it to be the default clip..
This part shows that you're actually getting data from the keyboard
here, gimme two minutes and i can show you what to look for
Okay, so that means that those actions are enabled
they'd say (Disabled) if they weren't
But there should be a list of bindings for each action, like this
it's written that there are no clips but what are these? idrk why it says no clips
I see that you are using control schemes -- you have one called "Keyboard" selected
(top left corner of the input action asset editor)
thtas not the animator..
The debugger does say that you're using a Keyboard control scheme
...but it has no devices!
bingo
go to window > Animator and then click ur Attack
You created a control scheme with no input devices in it.
that'll do it (:
you can see it behind, btw is set to default
ahh okay.. then im out of ideas..
Thank you for the help
anyone that has some other ideas
maybe ur animation needs a rig set to Humanoid or something
np, ty anyway
ok so I have a movement set up with W accelerate and the direction is the mouseposition, but anytime the player gets to the mouse position it shakes back and forth. I am an idiot who cannot come up with a solution
or Default* if its not a humanoid
Generic* i mean
im just guessing at this point.. maybe you'd have better luck in #🏃┃animation channel
@rocky canyon it was just a stupid Unity bug, when I try it it actually works, can't stand the amount of bugs it has 
(╯°□°)╯︵ ┻━┻
lol.. glad it was just that..
I have a button that I'm trying to change the "Fade Duration" of via script. I figured out how to access the property, but I'm not sure how to set it.
liek i said earlier Worker0 normally means u can ignore it
yep, thanks man, have a great day
yeah I had to listen to you earlier
where did you get .colors from?
ya, its not .colors.fadeDuration
I got it from this post:
https://discussions.unity.com/t/ui-button-fade-duration/241093
.colors and .fadeDuration are completely different lines and vars
ColorBlock eh?
Is this right?
neet
Why are the SerializeField fields not displayed?
compiler errors
or forgot to compile
you dont need colors at all
color block and button are completely different
Yes, but the point is that ColorBlock stores the data that was being asked about
yea but u need to access the ColorBlock to access the fadeDuration
it stores the fade duration
oh mb
What is that? Sry I just started coding
Do you have any compile errors and does the file name match the class name
if your script has errors, it wont show variables in the editor until they are fixed
An error with the way the code is written. It happens before the program runs.
Writing this is two compiler errors
void Start() {
public int myInt
}
ur compiler gets stuck @ the error.. and doesn't compile anything more
build it out and send them the files
itch is free
^ and can use a password
Itch also lets you send a secret URL to a project
I didn't realize that for a while, so I was making it restricted and then putting a password on it
Is this right then? I don't notice the fade duration changing on my button, so I need to know if this code is right or not to further troubleshoot this.
ColorBlock is a struct.
You must reassign it to the button after modifying it.
like the original example
Okay so I think I just need to add
button.colors = cblock;
Yep, that's it. Thanks!
i give up for the day
how do I assign a sorting layer to an object?
There's also a Sorting Group Component I think that u can add to ur components.. but thats new to me.
I tried to write the code shown in the screenshot, how do I get the parentheses through the void? if so, why is there void movement with me not, can someone explain that (C#)
It's called a "method" or "function". Not a void
void Movement()
{
...
}
This declares a method named Movement. The return type of the method is void, so it does not return anything atlal.
I do not know what "get the parentheses" or "why is there void movement with me not" means
thanks
I thought the problem was with the () but through your explanation I understood it now thank you
thanks
no worries
@modest dust using UnityEngine;
[System.Serializable]
public class EffectWrapper
{
public EffectType effectType;
public IEffect effect;
public EffectWrapper(EffectType type, IEffect effect)
{
this.effectType = type;
this.effect = effect;
}
} is this correct?
I dont know how to implement what you told me sorry , it is really advanced
quick question, what would be the most obvious reason why my gun recoil doesn't work on my player when aiming left and right, but if aiming down at their feet, the recoil pushes the player into the air?
Yeah, now it just lacks instantiating different effects
Because you've coded it that way. It not pushing you left or right might just be due to friction, but without seeing your setup we cannot see. Maybe you arent allowing horizontal movement
Look at ISerializationCallbackReceiver and the OnBeforeSerialize method
sorry, i should have said it doesnt work in the air either
based on the selected effectType, set the effect accordingly
this is all that I have
Lemme check my own EffectWrapper code
the only thing is that I dont know what is the overall result
why an scriptable object?
So that you can drag and drop it
If you don't want it then place EffectWrappers directly on the character
But what is the EffectWrapper exactly?
Sorry bro Im really lost with all this
EffectWrapper is for instantiating a correct class implementing the IEffect interface, based on the enum selected
but why do I need the enum?
To know which class to instantiate
If you want a projectile ability, you select EffectType.Projectile and it will instantiate ProjectileEffect
With any fields you might want to fill in
(I think you may need a custom property drawer for that though)
my god
i feel like this is going to be way too complicated for a novice to figure out
yes, I think so as well
My mind is exploding right now
I am very thankfull anyway
creating a system that can express a huge variety of abilities through configuration (instead of just writing custom code for each ability) is a difficult task
Attempting to solve that problem killed my first Unity project stone dead
Just straight up gave up because I couldn't figure it out
i've also ultra-killed at least one project that way
Basically something similar to this would be the result (the difference being only one effect instead of an array)
a real bugbear is when you get to things that aren't just instantaneous effects
like playing an animation and then doing something in response to events in the animation
Its really frustrating because I need this to have progress
this kind of thing is much more straightforward
I think Ill try to simplify it to things I do controll
perhaps we're not on the same page w.r.t. what these abilities will actually do
The reason it seems hard is because it's hard. Customizable abilities like this are very far from beginner concepts
thanks anyway bro
An ability, such as an attack, shooting a projectile, etc
A coroutine can be attached if needed / callbacks passed to do things when an animation ends / events trigger
I can give you a super detailed definition if you want
but I think Im going to overload you and you´ve already done a lot for this case
hi, can you tell me why this is happening?
not without seeing your code.
why bare you setting angular velocity and also manually rotating the transform?
why when i die then respawn and dash this happens (it dashes me backward opposites the way am moving)
player movement code https://codeshare.io/ApKxyw
player death code https://codeshare.io/MkjxJe
I kinda have a weird question, how does friction work with NavMesh?
Why does it work for the up and down but not left and right?
void UpdateMoveInput()
{
movementVector = pic.moveVector;
currentMoveState = movementVector.x switch
{
1 => MoveState.Left,
-1 => MoveState.Right,
_ => MoveState.None
};
currentMoveState = movementVector.y switch
{
1 => MoveState.Up,
-1 => MoveState.Down,
_ => MoveState.None
};
}
uh, I don't know, I'm a newbie
So then why did you write it like that
Cause my NavMeshAgents are just snaping to the NavMesh, but there is nothing actually touching there, so I think friction is just not doing anything....
Can that be?
because you're competely overwriting the variable on the very next line.
Anyways, I myself only worked on my own effects system just a few days ago and it was my first time doing anything like this, so it's pretty new to me too. The things I propose might not be enough to handle everything you might want to do - simply because I didn't yet implement it myself so I wouldn't know what would need to be changed or added to support it.. but it's a start, you can expand on what I said or research online / ask others, or simply take a pencil and a piece of paper and plan it out, see what you actually need and how you could implement it
Because your Y switch is going to set currentMoveState to either Up, Down, or None
ohhhhhhhhhhh
how can i avoid that then?
Thanks a lot
Don't overwrite currentMoveState
Evaluate the direction as a whole
I don’t understand, I tried to register the movement of the tank
So why are you setting angular velocity and also manually setting the transform's rotation?
I don't know I did it as it turned out)
does everything have to inherit from monobehaviour or can it be removed on some codes?
Depends on if you want it to be a MonoBehaviour
could you explain what a mono behaviour is
I'm clueless
A script that can be attached to a GameObject and receives messages from Unity
oh, a part of code add in?
ok so if it isn't attached to a game object then it isn't necessary
NavMeshAgents don't care about physics. They just smoothly move around on a nav mesh.
but there is nothing actually touching there
Colliders don't matter, and visuals definitely don't matter
that's exactly where I made a mistake, this is the code for the section that I wrote when I first started studying unity, thanks)
@rich adder how do I make it work
So to explain this more clearly. I want the enemies to use NavMesh to track the player. But I want the player to be able to push them back. Right now, since there is no friction, they just keep the force push momentum like for a veeeery long time. How can I go about this?
how are you pushing the enemies around?
Just applying Force on Impulse mode
Should I try with some kind of transform?
So you've turned off updatePosition on the agent, and you're using a Rigidbody to move the enemy around?
No, I just keep the agent running, and they just happen to have rb that can be pushed
Like, they don't seem to be interfearing much with each other
i'm surprised that works at all without some extra legwork
I use a CharacterController to move my entities around. I have a NavMeshAgent with updatePosition set to false so that the agent isn't allowed to actually move the entity.
I recreated your setup and the object is, indeed, sliding away
So... you are just using the NavMesh to calculate the path but not moving at all? What do you mean by a CharacterController?
a literal CharacterController component
I ask the agent what its desired velocity is and use that to determine which way to go
Adding drag to the rigidbody fixes that.
Mmmmm... yes, it kinda does, it still does slide more than I would like... but it is much better
the behavior with both an agent and a rigidbody is very weird. whilst the agent is moving, it mostly ignores me pushing a cube into it (other than getting moved so that it's not overlapping the cube)
but then sometimes it slides
hello im using pun 2 framework for multiplayer however the player gets destroyed after like 4secs
turning on interpolation on the rigidbody makes it stutter constantly
presumably since the rigidbody is forcibly setting the position every frame now
What debugging steps have you taken?
none
Start with the usual ones.
Debug.Log in OnDestroy would be a good start
any reference?
Yeah but where should i put
Debug.Log there
only enemy and i turned off enemyspawner
put a log on the player death function anyway
i tried commenting it
same thing happened
don't comment it
ok
I don't know your code at all
so it's hard to say where
add logs to all the places in your code that destroy anything
alright lemme see
showing the inspector of your player object would also be a good start
maybe it has a particle system or something for example?
i can't get my recoil to apply to my player horizontal direction, only in the y direction.
I think i know what line is causing it, but not sure how to correct it?
here's the recoil script:
Vector2 recoilForce = -aimDirection.normalized * recoilStrength;
playerRb.velocity += recoilForce;
and here's the movement script stripped down which i think is blocking it:
void Update()
{
rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
}
no i didnt move into particle system yet im trying to get multiplayer working first
because your code is setting the horizontal velocity every frame
do i need Time.Deltatime?
horizontal * speed
This is going to be your horizontal velocity
what? No. You're just guessing.
i was 🙂
Just a reminder that the solution was given #💻┃code-beginner message
how to make what work? You aren't replying to past responses, I have no idea what we were talking about..
Lol sorry I must have missed them
On mobile have to pull up the code again but basically stopping the ship from jiggling back and forth when it gets to the cursor
Was he helping you prior?
taken a long look at it and not sure how to correct it
the only was i can see if by doing an if statement bool when recoil is applied
but i'm sure thats not the right way about it
do you understand the issue first?
before we talk about solutions.
right so you'll need to either do something like use forces to slowly achieve the desired velocity, or disable the normal movement for a time after recoil
something along those lines
yes did you fix the normalizing first. Next I would just do a simple distance check to mouse worldPos using Vector3.Distance
i successfully disabled the normal movement using a bool and Ienumerator, but feel this isn't the right way about it?
Yes normalize is fixed
Wdym by "right way"? It all depends on how you want the game to work
it felt like it stopped allowing the player to control the movement for a splitsecond, especially with a rapid fire weapon
yes of course
that's what doing that would do, naturally
i have tried debugging everything thaty i found sus but it just uses something else im assuming any other way to be able to fix this?
so again you need to decide how you want it to work.
i tried using an Impulse force too, but that didn't work. Could you explain why?
same reason as before i assume?
And I will give that a shot
you are trying things quickly without thinking about the problem first
After you get the distance, if its too close don't let ship go forward etc.
If you want to do it where depends also if mouse behind ship or not, to see if can push forward or back
You can use vector3.dot
Thank you I'll give that a try in a bit
so I have this method that I'm trying to use as a part of a skillset representation in a character creator I'm working on; the trouble is I'm referencing an object ('rep' - the character data) that is currently - you guessed it - null. I know why it's null (I haven't assigned the relevant field yet), but all the tricks I've tried to make it not-null wind up being booby-trapped on me. Kinda just thinking out loud...
void UpdateMoveInput()
{
movementVector = pic.moveVector;
if (movementVector == up)
{
currentMoveState = MoveState.Up;
}
else if (movementVector == down)
{
currentMoveState = MoveState.Down;
}
else if (movementVector == left)
{
currentMoveState = MoveState.Left;
}
else if (movementVector == right)
{
currentMoveState = MoveState.Right;
}
else
{
currentMoveState = MoveState.None;
}
}
void UpdateButtonInput()
{
if (pic.BPressed)
{
currentButtonState = ButtonState.B;
}
else if (pic.XPressed)
{
currentButtonState = ButtonState.X;
}
else if (pic.APressed)
{
currentButtonState = ButtonState.A;
}
else if (pic.YPressed)
{
currentButtonState = ButtonState.Y;
}
else
{
currentButtonState = ButtonState.None;
}
}
```t
This works fine enough
but if im pressing 2 buttons at the same time, it will just default to none
anyone know how i can fix this?
Just write better logic
or if im pressing B and X, it will just default to B
You aren't handling diagonals
you also only have a single variable for button state
there's no way to disambiguate with that
It should default to the second?
nah it's an else if
This honestly seems like you're trying really really hard to basically just do a callback-based input system that's already provided by the Input System
sorry i meant for the movement, if its diagonal it defaults to none
because diagonal is not any of the vectors you're specifically checking for
by all means if there is an easier way i'll use it, but i just wanted to avoid linking the character to the player input directly
why are you complicating this so much 🤔
why not just directly pass e.g. movementVector to the code that controls the player
you're inserting this extra processing layer
What is movementVector? What is up? Are they Vector3s?
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/manual/Actions.html
You can subscribe to button events on whatever you like, which runs custom functions whenever an input value changes
they are vectors that i have defined in the fields
okay i think i know how i want to handle this
i want it so its like, if its diagonal, , it only does the last button pressed
blue arrow is what's supposed to happen where unit follows marker when spawned, red arrow is what's actually happening
unit spawns outside like it should, but then it just goes towards the building that's supposed to collide, unit is not selectable either because i'll select the building instead if i tried to select unit
does anyone know why this is the case? code is provided here and the spawn marker design
share your code with !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.
public void MoveUnit(Vector3 destination) {
// Set the destination for the NavMeshAgent to move towards
if (navAgent == null){
navAgent = GetComponent<NavMeshAgent>();
navAgent.SetDestination(destination);
}
else {
navAgent.SetDestination(destination);
}
}```
I mean it sounds pretty obviouisly like the destination you're setting is wrong
so you should log that, and log which object you're using as the destination
make sure it matches your expectations
okay one sec
might've done it wrong, is this what you mean?
ill show some more info
and log which object you're using as the destination
and then.. you know
does this match what you expect?
does this match what you expect?
this is looking at a prefab
are you sure you're not referencing SpawnMarker from the prefab?
You need to reference the one in the scene presumably
you have a lot of prefab overrides here
that bad?
It's indicative of disorganization if nothing else
so I'm not that confident all your references are pointing the right place
anyway... Debug.DrawLine would be helpful for example
to establish it's aiming at the right place
do i need to do that surely this is simple fix no?
It's probably a simple fix but only once we know what's going on
so for now we debug
debugging tells us how to fix it
problem is the unit isn't following the spawn point when i set it but travels towards the original position when i dont move it, even when i set the pointer at a location it travels to the original position
^ just wanted to say that if that gives a better idea
will the entire code be useful here
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
here's other one not as long
what is the best way to achieve something like this in rich text through code ?
What do you see in the log? Does it set the undesired destination that you mentioned?
yeah here @teal viper i spawn multiple units at different points and it prints the same coordinates
well i want two different allingmennts inn the same line, i dont see that in this documentation
Share the stack trace of the messages.
Share the SpawnObject code
you still haven't confirmed if those coordinates are what you expect or not
here
they're not
then you're simply referencing the wrong object
as I said before you're likely referencing the one from the prefab
not the one in the scene
Successive alignment scopes don't stack. If you put multiple alignment tags on the same line, the last one overrides the others.
-per the docs , you'll probably have to use two different text elements
probably, ill have a look now
how do i fix this then
reference the actual object you want to move to
prefabReference = Instantiate(prefab..
Move(prefabReference);
*prefabInstance would be a more correct naming.
so I'm working on a save system, and it'd be 1000000% easier, if, when a user makes a new file, there was a way to revert back to the values i set via the edit mode (i.e. say i have a script attatched to an object and the variable floatToChange = 1.0f, but later it's changed and saved as 6.132f and the user wants to make a new save file.) is there a way to do this?
I'm not sure if there's a nice way to do this
its common practice for a settings menu for example
i use Scriptable Objects to hold all my data
I have object objects to do this ig
I'm just concerned about writing every variable down manually since there are quite a few entries
whenever i create a new savefile all my data is already there
but i'll do like defaultDict = realDict in start and just copy paste the values in edit mode
i have the default for a lot of things- i just have a problem with items that have a ton of entries with unique values
oh yea, ive never done anything that substantial. so i wuldnt know the workflow
lol this is as far as ive gotten on the Inventory save system 😢
there are ways i could do it but if theres an easier approach id like to find that before wasting time
i was going to assign an int to each item the player can possess and just read thru them at the beginning of the game and give the player those items..
oh absolutely.. i feel ya
Hey, how do you do OnButtonUp with the new input system? it's surprisingly difficult to find any info on google
the opposite of this..
subscribe to the canceled event on the InputAction, or check WasReleasedThisFrame() on it
the dropdown in Interactions would have a Button up
thats alot easier than what i was thinking lol
oh nah it was the 3rd post in that thread.. myAction.cancelled
thanks
Hey yall I need a little helo. I've got a character controller and it works okay but I find that I have to sometimes mash the spacebar button to get my character to move. Anyone know how I might fix this? If it's relevant I'm using 2021.3.15f1, it's an old project of mine but I don't want to bother updating it and risk breaking more stuff lol.
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
you're reading input in FixedUpdate
input needs to be read in Update
Checking input in fixed update would do that.
Alright. Let me try to do that. Honestly I haven't touched this project in forever till recently...
you're also mixing up transform.Translate and Rigidbody motion
that's a recipe for sadness
That fixed it. Also not sure what you mean abouting mixing transform.Translate and rb motion. I probably got the original script from someone else on Google ages ago.
made a pretty good solution to my controller issue
just changed what was handling what and started using the player input actions instead of vectors
it means you're using two different forms of movement that aren't compatible. It will lead to bugs.
When you set the position of a transform, you're leaving the physics system in the dark
it will just discover that it's in a new position in the next physics update
(and if you have Interpolate turned on in the rigidbody's settings, it'll overwrite the position of the transform every frame, so your position gets lost)
this can cause you to go through walls, since your position has just been suddenly changed without letting the physics system have any say about what happens
You can set Rigidbody.position to teleport a rigidbody or Rigidbody.MovePosition to immediately move it to a destination
(the latter can hit things along the way)
Hi, I'm trying to make a 2D top down game and when doing collisions, I want to have the player "hug" the walls to give a sort of perspective, but I haven't found a way to get it to work. Right now, he stops far from the top wall, but I want to keep how far he is from the bottom wall. The walls are using a Tilemap Collider 2D and a Composite Collider 2D.
PlayerController Code: https://pastebin.com/h2u13fhg
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
i can control the other build but not myself any fix?
using PUN 2
did you use view.isMine
Yea
its normal when i load in by myself as soon as the other player loads in it switches
are these gameobjects already in the scene?
yea i used this PhotonNetwork.Instantiate(playerPrefab.name, randomPosition,Quaternion.identity);
!vc
Unity Version Control
Git
Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory.
!cs
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
Place colliders only on the lower level of the sprite/tile. The one that touches the ground. For your character that would be the feet. For the wall, that would be the lower part of the wall that connects to the ground.
!blender
A supportive community for Blender artists of all levels. Share your work, ask for help, and learn from others! https://discord.com/invite/blender
#archived-networking
Also go over the documentation and tutorials of the networking framework that you're using.
P.s. networking is not a beginner topic.
ok thanks
I'd probably play with the idea of shaving the colliders of these walls back a bit
or shaving down the player's collider
could do a double player collider such that you've got one near the center of the character, but also one around the character if you're needing the extra detection for attacking, ect
Hey so I recently started learning about PCG and I was able to get a randomly generating map. But can someone point me in the direction of how to do procedural path generation? (I'm trying to create a path along the tiles of the map) Just a process or anything will be helpful thanks!
I got basic movement down not linked to physics by making my own psuedo physics calculation and putting it in a seperate class
what is "this" ?
That is normal
Show the camera
It is likely set to solid color or whatever it is called. Blue is the default for that
Also, this is not a code question
Hi. I'm facing a problem. func() sometimes not even run but returns true.
// call in Update
public void Handle(Func<bool> func)
{
bool done = func();
}
You're ignoring the return value
Well you're storing it in a local variable that you don't do anything with
What makes you think it isn't running though?
i put debug.log inside func() and it doesn't log anything
Maybe Handle isn't even running
The camera component is collapsed...
it did run, i did put debug.log in handle too
Show your real code then
how do i uncollapse ot
Trust me it can't return anything if it's not running
Click the little arrow next to the name...
mb
oh i see now
before it was the map
and ive connected it to player
all of a sudden its going to its default color?
public void Handle(Func<bool> func)
{
if (_doneFlag) return;
_timer += Time.deltaTime;
bool done = func();
Debug.Log(done.ToString() + (transform.position - _destination).magnitude.ToString() + ((transform.position - _destination).magnitude < _stopDistance));
if (done && (_behaviorPath.GetCurrentAction().ActionDuration() < _timer))
{
_doneFlag = true;
_doneAction = true;
_timer = 0f;
}
}
public bool Move()
{
if ((transform.position - _destination).magnitude < _stopDistance)
{
if(!_navMeshAgent.hasPath && _navMeshAgent.velocity.sqrMagnitude == 0f)
{
Debug.Log("Move true " + (transform.position - _destination).magnitude);
return true;
}
}
Debug.Log("Move false");
return false;
}
public override void FixedUpdateState()
{
base.FixedUpdateState();
_npcController.Handle(_npcController.Move);
}
And...the rest? NPC controller.Move?
Is it the one right above?
What is the type of this script? What's the type of that NPC variable?
Not clear
@summer stump bro?
Yes. it's the Move() method above, i copied that function from other class.
How do you know?
It might not be
This isn't enough code to be sure
you dont have skybox material
Move() and Handle() method are implement at NPCController class
public class NPCMoveState : NPCMovementBaseState
{
public NPCMoveState(MonoBehaviour entityController, Animator animator) : base(entityController, animator){}
public override string StateName => "Move";
public override void EnterState()
{
base.EnterState();
_animator.CrossFade(LocomotionHash, 0.1f);
_npcController.OnMove();
}
public override void FixedUpdateState()
{
base.FixedUpdateState();
_npcController.Handle(_npcController.Move);
}
}
This still doesn't tell us what _npcController is
...?
It's a class inherits from monobehavior, i create it for NPC control
public class NPCController : MonoBehaviour
{
[SerializeField] private BehaviorPathTransition _behaviorPath;
[SerializeField] private bool _doneAction = true;
private BaseStateMachine _movementStateMachine;
private BaseStateMachine _actionStateMachine;
private Animator _animator;
...
}
In this Move function it is possible for it not to print anything
If it enters the first if statement but not the inner one
It is still running though
The executed order is NPCcontroller Update -> Statemachine Update -> State Update -> Handle -> Move. I think ...
@rich adder sorry bro im not understanding it was fine before idk what i did
i mightve miss clicked smt a while ago
and idk what it is
can you just explain to me what to d
u sed smt abt skybox?
no way of us knowing what its supposed to look like
also not really a code question.
cmon man plz
no one on other ones answer
until the next day
shall i just delete and get it tagin
nvm that didnt go well
you haven't really explained whats wont with the blue
all i see is that camera has SKybox set but its blue, meaning Lighting tab has no skybox material assigne
Sorry, putting my daughter to sleep. All I can say is that it says skybox 🤷♂️
Did it switch from 3d to 2d? I see it is orthographic
oh nw bro, 2d here
and which Z position is your bg
Check z levels
The z position of the transform of the object the camera is on
Cameras won't render things they are too close to
APPRECIATE U GUYS
Next time ask in #💻┃unity-talk btw
Sure. I'm not good at English, it's hard for me to describe this console log. sorry.
I don't see any Move False or Move True
Nor any of the log from the Handle function
None of this code is running at all
@summer stump one last thing
the size of my camera got messed up
z is -10
wats x and y
default
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ButtonDoor : MonoBehaviour
{
public int buttonNumber; // The button number assigned in the inspector
public AudioClip buttonPressSound;
public Sprite pressedButtonImage;
public Sprite normalButtonImage;
private List<int> correctOrder = new List<int> { 1, 2, 3, 4 };
private List<int> pressedButtons = new List<int>();
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
// Play sound and change image to pressed state
AudioSource.PlayClipAtPoint(buttonPressSound, transform.position);
GetComponent<SpriteRenderer>().sprite = pressedButtonImage;
// Add the button number to the pressedButtons list
pressedButtons.Add(buttonNumber);
// Check if the pressed buttons match the correct order
if (pressedButtons.SequenceEqual(correctOrder))
{
// Trigger fade animation on the Lock object
GameObject lockObject = GameObject.Find("Lock");
Animator lockAnimator = lockObject.GetComponent<Animator>();
lockAnimator.SetTrigger("FadeOut");
}
else if (pressedButtons.Count == correctOrder.Count)
{
// Reset button states if incorrect order
ResetButtonStates();
}
}
}
private void ResetButtonStates()
{
// Reset pressed buttons and change image back to normal state
pressedButtons.Clear();
GetComponent<SpriteRenderer>().sprite = normalButtonImage;
}
}
I got this error which I don't get
I don't see any Move False or Move True
missing LINQ
gpt forgetting usings 
mising LINQ?
the computer right now doesn't know what .SequenceEqual() method is on List aka Enumerable
oh
the function you copied and pasted is missing the namespace to help "find" it
Your IDE should be able to add the missing namespace. If it's not underlining errors in red you need to configure it. !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
IDE?
ctrl + . on the red underline if you have it, it should suggest it
Visual Studio is your IDE
Wherever makes sense for your project. Default is of course 0,0. But in 2d that may change
if i recall correctly yours is Visual Studio and is configured
I feel like I have told you to configure your ide so many times in the past
ok
its configured but they only show the error from unity for some reason lol
oh yeah mine is visual studio
I just meant because they seemed bewildered by the word IDE hahaha
They have definitely heard of it before
yeah they do that lol "you need this to be a variable"
"A variable? ?"
press ctrl + . on the error it will give you suggestion to add the proper namespace
I pressed ctrl + . but nothing is happening
erm did you do it by selecting the underlined portion first
(make sure cursor is on the underlined word)
Need some help here what do you guys think is the best way for camera following I've heard a few options
- Cinamachine
- Lookat
Cinemachine
Its that good?
Gotchu gonna take a look
Then you need to configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
hey i know this is a super beginner question but i'm trying my hand at a recreation of pong, how do i stop the paddle from continuing to float upwards after i've stopped pressing w? i have a screenshot of my code but i don't really know how to show you what the paddle is doing lol
could set vel to 0 on key up
Could also just use GetAxis for Vertical and it gives you W/S or UpArrow/DownArrow with float value
sweet thank you i'm still learning what functions and methods i have available to me lol
here is the one I mentioned https://docs.unity3d.com/ScriptReference/Input.GetAxis.html
ide ? ?
what would I put in place of the Debug.Log("Success!"); in order to make the object transform its position to the object that the raycast hit?
this is giving all the info you need from rayhit
just assign the object's position to the hit object's position . . .
okay, i didnt think it was so difficult, fsr im getting tutorial hell syndrome from this lil road block
this task is not difficult. it's very simple and only one line of code . . .
you have to look at the information provided to you . . .
yeeyee
if you have the object the raycast hit, then you have access to its position, therefore, you can assign the original object's position to that position . . .. . .
bro this has colliderinstanceID? so many things i could do with this, macadamia nuts, almonds, walnuts, acorns
why would you need colliderinstanceID?
something to do with joints
Hey guys, im helping a friend to start coding in C# Unity.
but his editor seems strange, the Debug.Log does not got autocompleted neither have color
Anyone knows what's missing?
He is using VIsual Studio 2022
try regen project files, if that doesnt work right click the solution inside Solution explorer window, and do Reload with Dependencies or watever is called
assuming the Unity Workload is already installed..
it was working everything just fine yesterday
well the (i) icon next to it says there is problem
yesterday is not today lol
!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
!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.
whats that other one? it allows multiple pages of code?
how come my lil guy isnt staying put?
Not entirely sure I understand how the CollisionMatrix affects the calling of OnTriggerEnter2D. Does it only work on OnCollisionEnter?
im not using any colliders with ontrigger, just using it as a visual
Sorry, it wasn't related to your question
Is it impossible to subscribe to scriptableObject functions? I've been getting reference is not an instance of an object errors when I try to do this. I'm trying to hook up InputActions with one of my scriptableObject function that handles shooting
im thinking my update function is still saying that grabpoint isnt null, so it moves it to the presumed grapoint location, and oo my bad 😮
pastebin or https://paste.myst.rs/
I've set up my CollisionMatrix to have "pickups" affect only "pickupZones" and yet OnTriggerEnter2D gets called when anything touches it
providing the actual error message and the relevant code would be helpful . . .
That... does not make a lot of sense for me
It affects all physics queries, so it'd affect triggers too. Note that the Rigidbody is what receives the callback, even if the collider is on a child object
ya, only colliders w/ pickup should interact with playerpickupzone
In that case those objects and only those objects should be interacting
something more is going on.. do you have the layers set up correctly on each object?
Are you sure you set up 2D physics and not 3D physics layer matrix?
I was not aware there was a difference
there is indeed
indeed there is . . .
praet with teh clutch
is indeed there
i have two scenes
my character has dontdestroyonload
but when he goes to the other scene, all the other objects in there (enemy, camera) and their scripts don't have the player set as their reference
how do i go about making it work?
if your player isn't going to be in the scene you will need to resolve the reference to it at runtime, rather than drag & drop in the editor.
If there's only one player you can go with the singleton pattern - using a static reference field.
Another option of course is FindWithTag
is there an alternate option? can i have another player in every scene and just copy the previous player stats throughout the scenes?
and which way is the cleanest/most optimal one? how do they do it in Hades where you move through rooms and your character stays the same across
Doing that copying of stats will require similar referencing tricks though - you'd need something to track the stats across scenes
There is no general answer here
every game is different
well, if i were you and i were to do a very simple two rooms game with coins you gather through the rooms and want to keep the coin counter and some other arbitrary stats
which way would you personally do? 🥹
I have a line of coded i dont understand
int damageToTake = ignoreDefence ? damage : CalculateDamage(damage);
im not familiar with the colon and the questionmark
how do you write a piece of code that you don't understand? it's a ternary operator . . .
it was someones code i was looking at
me either
if(ignoreDefence){
damageToTake = damage
}else{
damageToTake = CalculateDamage(damage)
}```
ok so is that basically what its saying
<condition> ? if : else
Keep in mind, ternary operators only work when assigning a value
value = condition ? if : else
i mentioned it is called a ternary operator. you can google the rest to find out . . .
i dont wish to see my projects or my teams project got infested by ternaries if tho lmao
its hard to figure them out if the ternaries got too long
there is no reason to nest ternaries. that would definitely be hard to read . . .
if(A == B) {
doA();
}else{
doB();
}```
im okay with this
```cs
(A == B) ? doA(); : doB();```
this won't work bc ternary operators must assign a value . . .
#💻┃code-beginner message
ternary stuff is ugly
sad
you can create an extension method to fix that . . .
I was kinda curious - and this is the least ugly I could get "ternary with void methods"
void A() {}
void B() {}
void C() {
Action x;
(x = (true ? A : B))();
}```
yeah, that's what i did at first, haha . . .
now i use a boolean extension so it doesn't look too bad . . .
void A() { }
void B() { }
true.Ternary(A, B)();
public static Action Ternary(this bool b, Action @true, Action @false) => b ? @true : @false;
why not just invoke them inside
then you don't need the extra ()
but yeah that's cute. I was just thinking a static non-extension too.
how so?
public static void Ternary(this bool b, Action @true, Action @false) {
if (b) @true();
else @false();
}```
then it's just cs true.Ternary(A, B);
oh, i see, by removing the ternary and changing the return type to void . . .
Oops I accidentally the void 😆
yeah, i returned an Action in case of assignment . . .
i guess it's not really needed . . .
It's not that bad when it's simple.
It would be relative to aesthetics.
how do you do something like this? a list (elements) within a list (plain font, outline font, outline shadows font, shadows font)?
I think you will find that is a List or Array of a plain C# serializable class or struct containing the variable definitions
i dont understand sir, can you give me an example?
class A {
public Font aFont;
}
class B : MonoBehaviour {
public List<A> aFontList;
}
along with putting [Serializable] above class A
not entirely sure where i'm supposed to post this, but every time i press play in the editor and press a button to move, the entire unity editor freezes and becomes unresponsive and i'm forced to close it in the task manager, are there any common reasons this happens?
An infinite loop is the most common cause
that seems to have been the problem, though i'm not really sure why my code caused one - i fixed it though, so thanks :)
Hey guys.This code spawns 10 rocks on random coordinates in my terrain.I used sample terrain to get the y coordinate but the Y coordinate isnt coming correct.The first rock always spawn on y lvl 0 and then rest on random coordinates. could someone help me
i have this error since yesterday but couldnt get any reason
Dont you think it might be a good idea to only use Ycoords AFTER you have calculated it?
wdym
read your code from top to bottom
I bet your first ycoordinate is always 1?
No it doesn't
code is executed from top to bottom, you cannot read a value before you have written it
then your testing is faulty, that code as written does not work
To clarify, you create your SpawnPos before you calculate your Ycoordinate. In that case your first instance is always getting the "default" value of your Ycoordinate
!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.
Mornin' all. I think I'm having a bit of a spanner moment.
Really simple onTriggerEnter.
Script lives on an object that hits the 'SectionRemover' object and should get destroyed (yes, this will be pooled once it's working).
Weird thing is, the debug is being fired, but the object isn't getting destroyed.
Am I being an idiot? lol.
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("SectionRemover"))
{
Debug.Log("Collision");
Destroy(gameObject);
}
}
It will be destroyed at the end of the next fixed update
The object(s) never get destroyed though. 😕
You sure you're not expecting the other.gameObject to be destroyed?
In the video, this script lives on the 'ground rocks' so when they hit the two objects that form the V Shape they need to be destroyed. As you can see, the debug gets triggered, but the objects remain. It's very odd.
For the heck of it, try just disabling the gameobject
Okeydoke. uno momento 🙂
or print out the object being destroyed
There's hundreds of those log messages. How do you know the logs for those rocks specifically are being printed?
Aaah, I see what's going on. It's the LOD's, I have two of the objects that don't have LOD's set up yet, and they disable fine, it's the LOD'd one that aren't. Sokay I know how to fix that.
So yeah, was being an idiot. lol.
how to stop these clones from floodign the scene
At a guess, instead of using SetActive(false) use Destroy
in that case parent them to an empty game object
why isn't my variable showing on the inspector?
unity doesnt serialize arrays of arrays
the workarround is to create a serializable struct containg your other array and make a list of that struct
oh, ok ty
how do i check a list or array to see which item has the correct value for example lets say i have a list of boxes with a number variable attached i want to find the one that number variable is 5 how would i do that
hello, i've encountered a problem in visual studio, the code works, but Monobehavior and Rigidbody2D aren't being highlighted. i've followed the fix that've been refered to by a lot of websites, but that doesn't seem to fix the problem. how can i fix this? https://forum.unity.com/threads/intellisense-not-working-with-visual-studio-fix.836599/
You need to configure your !ide to work with Unity
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
tho the variable shows up in unity and i can put the rigidbody in there just fine
Your ide does not interact with Unity, it just supports you with the code you write
Currently it does not support you with Unity related code
Once configured it will work
i'll try to
How do you guys feel about || Russia || ?
Quite a weird topic for a unity server
Yes, I understand... By the way. Could you tell me what are the main differences between version 2023.2.15 and Unity 2022.3.22f1?
there is no off topic on this server
I'm thinking whether it's worth switching to a new one
do not use a non LTS version unless you really know what you are doing
Sorry
Guys, maybe someone has a good template for a Shooter ||unitypackage|| ?
Anyone?
Make a hash map or loop through the list
Look for LINQ first
List<T> already has a FindIndex method.
Does anyone understand Photon?
It takes a System.Predicate<T>, which is a function that takes a T and returns a bool
List<int> nums = new() { 1, 5, 3, 5, 7, 8, 0 };
int index = nums.FindIndex(x => x == 5);
another example
oh yeah i forgot first outputs the value, not the index 😄
List<MyClass> things = new();
int winner = things.FindIndex(thing => thing.IsCorrect());
if you've never seen the => syntax used like this before, this is creating an anonymous function
it's a function with no name
you're probably used to seeing things like this
void Update() {
// do stuff here
}
this is a method: a function with a name that's part of a class
Anonymous functions are useful for writing logic that you only use in one place
So both of these would work equally well
private bool Decider(int input) {
return input == 5;
}
public int FindIndex() {
return myList.FindIndex(Decider);
}
public int FindIndex2() {
return myList.FindIndex(num => num == 5);
}
assuming that myList is a List<int>
anonymous functions can capture variables, too, which is useful
public int FindIndex3(int desired) {
return myList.FindIndex(num => num == desired);
}
Well they said it’s a list of boxes (I assume GameObject) with variables attatched to them
So would it look like? ```cs
private bool Decider(MyClassName input) {
return input.variable == 5;
}
Right.
This is new to me too so I’m curious
the parameter should match the type the list contains
and then it should do some work and return a bool
Out of curiosity, how do you make a method that passes a function as an argument?
Like what’s the syntax for it?
Suppose I have a button on the canvas, and some objects in the scene that respond to clicks.
How do I make it so that, even if a canvas button overlaps with some other object in the scene, when I click the canvas button, don't make the other object respond?
things I know and have tried:
I know how to use OnMouseDown etc to detect a click on a collider, I recently found out about OnPointerClick etc to detect a click on a UI element on the canvas, and when searching I sometimes see Input.GetMouseButtonDown(0) for generic click detection.
I tried to overlap a canvas element and a scene element, and when I clicked, both object's click events triggered. I don't know the order of operations here so I don't think I can set a flag in the canvas element that makes the scene element do nothing on click.
there's usually a bool on most UI components that say like Raycast target, or Blocks Raycast (meaning it takes in raycasts hits)
oh but you're saying both are activating
I'd stick to a single method, preferably OnPointerClick interfaces and friends.
Turning off "raycast target" makes the canvas object's click event go away, but still triggers the scene object's click event.
also im trying to make a list / array containing all gameobjects that have the playerstats script on them im not exactly sure if im doing it right here is what im trying
PlayerStats[] playerstats = PlayerStats.FindObjectsByType(PlayerStats, true, false);
is that a bad way to do it (i also know that has a error im looking at the documentation right now to fix that)
Right, so OnMouseDown does a physics query, and IPointer uses the event system
Generally using Find methods is bad
I guess in this case you want to collect the components for stats so I guess it makes sense to do this here
The System.Action types cover functions that return void, and the System.Func types are for functions that return something
System.Func<int, bool> takes an int and returns a bool
They're called delegate types.
Hmm, interesting
So his would be System.Func<MyClass, bool>
You can declare your own delegate types to get something with a name and with named parameters
public delegate bool MyPredicate(int input);
Oh, IPointer does also use a physics query, but also the graphics raycast?
I never thought about tossing that on 3D objects
is there a way to adjust pixel perfect camera size without ruining the resolution ?
For your information:
- My canvas object has an
Imageand aSimpleClickLogger(script). - My scene object has a
Sprite renderer, aBox collider 2D, and the sameSimpleClickLoggerscript. - The script contains both
OnMouseDownandOnPointerClick.- The canvas object only fires the
OnPointerClick, the scene object only fires theOnMouseDown.
- The canvas object only fires the
the reference resolution tells the camera roughly how many pixels you want to see on the screen
but the camera is only going to be able to snap to certain zoom levels
Hello. I'm trying to make an enemy that moves along the exact route that the player took. Any ideas on how I could go about this?
Well, one idea you can go with is checking if the Mouse is currently over the UI and preventing MouseDown event from executing (by returning early)
what is the 16:9 resolutions i can use for the pixel perfect ?
or vice versa
Is that documentation available for Unity 2022? (Sometimes I google some docs, it gives me 2018 or 19, and when I switch to 2022, I can't find the relevant doc)
I did try finding the most recent docs of it, but it's giving me a hard time.
If you get sent to the home page when you try to switch to 2022, that probably means they renamed the page or merged it into something else
It's not deprecated though
2022 doesn't have a page for UnityEngine.EventSystems on the side bar ... somehow
Make a list of Vector2s that adds a player position every couple frames/every frame, then make the enemy move toward the first one, and then once it gets within a certain distance of the first vector, move on to the next one and repeat
More efficient would be saving vector2 points, only if the direction changes substantially
UI stuff got moved into a separate UI package.
This is a common annoyance. I'll get old documentation from when it used to be part of the "core" libraries
(I also prefer the old documentation's look to that of the package docs, tbh...)
Thanks, I guess. Package docs are ... more annoying in my experience too (had more trouble finding how to change text in a TextMeshPro text component, had to resort to google and chatGPT)
the TMPro documentation is..not great
enjoy reading through the 300 methods without any comments
The ultimate "Try It and See" experience
i'm trying to learn to do more complex TextMeshPro stuff without just copying code from examples and modifying it
but...yeah
Any good character controller script that Does not slide around on the floor
a character controller does not "slide around" unless you tell it to
so, most scripts that use a CharacterController will already do this
Currently trying to do an enemy LOS detection system, but I don't think I'm doing the raycast right since it can see right through the obstacles. ```cs
void Update()
{
Debug.DrawLine(transform.position, targetLocation.position);
detectionAngleRadians = detectionAngle * Mathf.Deg2Rad;
detectionAngleFloat = MathF.Cos(detectionAngleRadians);
targetVector = targetLocation.position - transform.position;
distanceToTarget = Vector3.Magnitude(targetVector);
if ((Vector3.Dot(transform.forward, targetVector) > detectionAngleFloat && distanceToTarget < detectionRange) && entitySpotted == false)
{
Ray ray = new Ray(transform.position, targetLocation.position);
if (Physics.Raycast(ray,out RaycastHit hit, distanceToTarget + 1F, obstructionMask))
{
OnPlayerSpotted.Invoke();
entitySpotted = true;
}
else
{
}
}
else if ((Vector3.Dot(transform.forward, targetVector) < detectionAngleFloat || distanceToTarget > detectionRange) && entitySpotted == true)
{
Ray ray = new Ray(transform.position, targetLocation.position);
if (Physics.Raycast(ray, out RaycastHit hit, distanceToTarget + 1F, obstructionMask))
{
}
else
{
Debug.Log("Player has vanished");
OnPlayerVanished.Invoke();
entitySpotted = false;
}
}
}
swapping them over yields the same result. And I've definitely got the layermask set up in the inspector and on the walls
You formed your ray improperly
Ray ray = new Ray(transform.position, targetLocation.position);```
A ray takes a position and a direction
you've given it two positions
If you want to cast between two points you can use Physics.Linecast
Linecast takes start and end positions
why does my mouse shows error
Have you read the error?
The error message will tell you what the problem is.
unless that's the font there's a space between the Debug and log function
there is a space there but it doesn't matter and isn't related to the error.
then?
read the error message
share it with us if you don't understand it
none of this is you reading the error message
but clearly you're missing using UnityEngine.InputSystem;
your IDE should suggest this for you automatically
there we go, that fixed it. Although now I need to figure out why it won't behave the same way in a different ai state, but I can figure that myself. Cheers
oh ok
is there a way t o not use new Vector2's every time? this is normally called each frame, so idk if its very efficient.
public static Vector2 MoveX(Vector2 velocity, float inputDirection, float speed)
{
Vector2 moveDirection = new Vector2(inputDirection * speed, velocity.y);
return moveDirection;
}
Creating a new V2 each frame is not a big deal or anything to worry about. But you can just do cs velocity.x = inputDirection * speed; return velocity;
this will actually indeed be slightly more efficient.
Hey, so I'm trying to trigger a scene switch inside my game that would bring up an options scene and inside that scene use an attached script to resume the game, but I'm getting a runtime error where none of my inputs are reading in despite both scripts being properly attached. Do I need to instantiate a Scene object and check for its .BuildIndex inside Update() instead?
//GameController.cs
void Update() {
if (Input.GetKeyDown("p"))
{
SceneManager.LoadScene(2); // Brings up option scene
}
}
//OptionsBehavior.cs
void Update() {
if (Input.GetKeyDown("p"))
{
SceneManager.LoadScene(2); //Returns to game scene
}
}
Don't just say "a runtime error". Share the error message
That’s the character controller script
that's the issue, there isn't any error message, simply doesn't work as intended (I think runtime was the wrong word to use lol)
How do you expect it to work and what is happening instead?
Add Debug.Log to make sure your code is running when you expect it to run.
yep did that to test and no output
then your code isn't running at all
switching from one scene to another when p is pressed and viceversa
This is the guidelines for how to properly post !code. The two options are large scripts or local inline snippets
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
You need the script to be attached to an active GameObject in the scene, and to itself be enabled. Then Update will run.
Also both of your scripts seem to load the same scene (scene 2)
Sorry I didn’t know
Oh okay, I didn't know you could return parameters of a method, thank you!
they are the same as any other local variables declared in the method.
unless they are marked with ref out or in
I've learnt something new today 😊
then there are special rules.
bit of a typo, but in the code 0->2 and 2->0 (double-checked). gamecontroller script is attached to a GameObject (the player) and the options script is attached to a canvas object so idek what's up
I can share the whole script if that would help
SHow your code with the logs and show which objects they're attached to (in which scenes) and then show your console window when you run the game and press the button in each scene
yes the whole script would help.
Now i'm noticing that it ends up drawing a line from the centre of the world to the enemy instead of the enemy to the player, which is odd. it's drawing a line from the enemy to the hit point, so shouldn't that just point to the player? Don't know if i've just gone barmy and forgotten something. ```cs
void Update()
{
detectionAngleRadians = detectionAngle * Mathf.Deg2Rad;
detectionAngleFloat = MathF.Cos(detectionAngleRadians);
targetVector = targetLocation.position - transform.position;
distanceToTarget = Vector3.Magnitude(targetVector);
if (distanceToTarget < detectionRange) //Target is within range
{
if (Vector3.Dot(transform.forward, targetVector) > detectionAngleFloat) //Target is within FOV
{
Ray ray = new Ray(transform.position, (targetLocation.position - transform.position).normalized);
if (Physics.Raycast(ray, out RaycastHit hit, distanceToTarget + 1F, obstructionMask))
{
//Hit object
Debug.DrawLine(transform.position, hit.point);
OnPlayerVanished.Invoke();
entitySpotted = false;
}
else
{
//Hit target
Debug.DrawLine(transform.position, hit.point);
OnPlayerSpotted.Invoke();
entitySpotted = true;
}
}
else //Target is outside of FOV
{
OnPlayerVanished.Invoke();
entitySpotted = false;
}
}
else //Target outside of range
{
OnPlayerVanished.Invoke();
entitySpotted = false;
}
}
Ah, just noticed those errors
not sure why it's saying there's a null reference when each state appears to be using the detection system fine
You've got it collapsed so order isn't known
Code to files: https://paste.ofcode.org/mLHCtp46nAfVdzG8DpNVXf
Objects it's attached to in screenshots (Player is in scene 0, options is in scene 2, and menu is in scene 1)
Ok, so it actually works in scene 2 and switches to scene 0 which is awesome. Wasn't sure on how to export logs so if you lmk I can send them too
The two scripts you searched for are not the ones you shared code for
that would be Menu.cs and PlayerMovement.cs
sorry, PlayerMovement.cs = GameController, I just gave it a different name 😅
I never shared something called Menu.cs though
which is still not related to the searches
Yes you did in this code
This doesn't work 🤔
the filename needs to match the class name
yep I changed the class name
when are you doing all this
you just shared a screenshot with them not matching
So if you just did it now go re-check that the scripts are attached properly and try again
just did 👍
apologies for the confusion
you reckon the above component might be interfering with it @wintry quarry? there aren't any overlapping keybinds methinks
I'll disable and try
Well if you are using the new input system your old input system code generally won't work
unless you have active input handling set to Both in project settings
have you shown your console window yet?
I get this from the options scene but no output in-game from switching to the options scene, for the log how do I export it?
could always be a VS quirk, but I noticed that the highlighting for the function in the file where it's not working isn't on
oh. my. god.
you were absolutely right. I had another file opened on VS called playercontroller from another project that I was editing this whole time, whereas the one that was being used was playermovement.
and now it works
ty for the help
didn't work :/
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Unity.VisualScripting;
using UnityEngine;
public class GameInput : MonoBehaviour
{
private PlayerInputActions playerInputActions;
private void Awake()
{
playerInputActions = new PlayerInputActions();
playerInputActions.Player.Enable();
playerInputActions.Player.Interact.performed += Interact_performed;
}
private void Interact_performed(UnityEngine.InputSystem.InputAction.CallbackContext obj)
{
OnInteactAction? Invoke(This, EventArgs.Empty);
}
public Vector2 GetMovementNormalized()
{
Vector2 inputVector = playerInputActions.Player.Move.ReadValue<Vector2>(); ;
inputVector = inputVector.normalized;
return inputVector;
}
}
wtf is my error here?
oof!
your error is not posting the error
Show the external tools menu
Maybe this line that makes no sense?
OnInteactAction? Invoke(This, EventArgs.Empty);```
but yeah show error