#💻┃code-beginner
1 messages · Page 22 of 1
i have visuial studio
If in the first place you dont have this checked it means you didnt even follow the tutorial 💀
It is checked?
Okay what about all the other steps
Also cheeck on this
screenshot your entire IDE window with the solution explorer visible
chances are solution needs rebuild
By the way does someone know whats happening for me with the material? 💀
yeah the solution isn't open
close visual studio, go into unity and regenerate project files. after that double click a script inside unity to open it in visual studio
also if there is a compile error all this config won't do much
how do i regenerate project files (sorry for being dumb)
the big button that says regen
in external tools
edt > preferences
you'll see it when going through the configuration steps 😉
If you followed the instructions you'd see it pretty clearly
-_-
You'll need to do lots of reading thru documentations if you plan on making a game, better get used to it
where tf is regenerate project files
shhhh...
☠️
To be clear, Gotta select the External Script editor, as shown in the guide
ty
have you tried actually doing what the configuration guide says?
doesn't follow the instructions
tHe InSTruCtIoNs DoN't WoRK
No NeoVim, very disappointing... 
now Vs looks diffent
how would you use a debugger with neovim
i think its right
You attach it
reference the script
access the member, change it
So I'm building some logic to have a crop growing section of my game. I have two tile maps, the base and the crop tilemap. My crop tilemap is at order layer 1 while my base is 0. Why is my mouse position reading the base layer even if I draw on the crop layer? e.g. if base has tile 1 and crop has tile 2, I log the tile that is being clicked and it says tile 1 is the one being clicked no matter what. How do I get my mouseposition to read the highest layer and not only the base layer?
yep, the problem is that pipes player collision is in a prefab
get a reference to that component, then modify the public variable using the . operator.
also !code 👇
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
does it look right now?
is it bad to be setting an image's color for a transition this way?
_image.color = new Color(_image.color.r, _image.color.g, _image.color.b, alpha);```
i mean
it should be fine
all I want to do is change the alpha, but it's readonly
it isn't bad, but a slightly better looking way which does exactly the same thing would be this:
var color = _image.color;
color.a = alpha;
_image.color = color;
make a copy and pass it back
Ah, proof you didn't do the guide you were told to do a whole bunch
.....
bro is being ganged on 💀
but it works now right?
yes, it is now configured correctly
moral of the story: just don't lie
and u don't get roasted
moral of the story: i suck at following guides
yeah, but this script is in a prefab... so how i cold do that?
did you look at the side bar on that link?
you're in for a surpise then..
shouldve just read it 💀 🙏
true, let me see
now can somebody who isnt mad at me rn help me with my problem
sure
Translate is teleportation, that's going to ignore all collisions
They're not mad, just disappointed...
so what can i write instead
"i read it 5 times"
i don't know what your actual problem was, but you're moving via the transform so you aren't going to be respecting colliders
but what word can i use so i respec colliders
You'll need to move with a Rigidbody or CharacterController
that dont help
I NEED PRECISE LINES OF CODE
or else my stupid brain cant understand
no
yes
No handouts
no

go find a tutorial
.....
what a helpful response!
but for real, there are hundreds of tutorials for moving via character controller or rigidbody
or if you really want to move via the transform, you can do even more work by checking for collisions manually using physics queries and the like
dude i only understand half of those words
Then you should look them up
exactly. so go find some tutorials to copy from. or you can go through some beginner courses to actually learn wtf you are doing
hint: click the Referencing Prefabs from Scenes link in the side bar
yeah i know
what i dont understand is how can i access from pipes collision to a var on pipes controller...
probably its explained... but i dont get it
honestly for what you are doing you should learn how to use events because that would be the easiest way to do this
this is basically a nonsense sentence. you may want to think about rewording that in a way that actually makes sense
but your issue appears to be that you want to access a variable on your PipesController. not a variable on your prefab. go look at the other ways to reference the PipesController from the instantiated pipes
or just use an event like i suggested
What is it that you are trying to do
Hey I had some warnings I was trying to fix but clear on start was on and now there not there how do I find them again?
Ill try to tell you my best
Wait for them to come back
Wdym?
If they don't come back, then problem solved
But wait for what?
The warnings to come back
And would a warning just fix itself like that if it didn’t come back?
it depends what the warning was
if it comes back, then you know you may need to address it. if it doesn't, then it likely was just a one time issue
hence this #💻┃code-beginner message
“The result of this expression is always ‘true’ since a value of type ‘OVRInput.Button’ is never equal to ‘null’ of type ‘OVRInput.Button?’” This was the error
Well warning not error
You're checking if something is != null when it can't ever actually be null
then go to where the warning was pointing you to and fix it
PipesController has got a var called hasCollisioned. I have another script that belongs to a prefab called PipesCollision, and i wanna make that hasCollisioned var true from the script PipesCollision. Is that clear?
but still, events are like perfect for this
Yeah but there were a bunch of those warnings, and I can’t see all of them anymore
Okay, so, when you spawn in a PipesCollision, give that thing a reference to PipesController
So, go work on fixing them when they come back
look for them in the Error List in your IDE
Where do I find that?
in your IDE
surely it is configured so that you can see errors and warnings in the code
Oh so VS?
yes
Ok
hello freinds,can you guys help me improve my object grabbing code? (yes, again imitating half life 2), here it is: ```public class PickupableObjects : MonoBehaviour
{
[SerializeField] private LayerMask layerMask;
[SerializeField] private Camera PlayerCamera;
[SerializeField] private Transform PickupTarget;
[Space]
[SerializeField] private float PickupRange;
private Rigidbody currentObject;
private void FixedUpdate()
{
if (currentObject)
{
Vector3 directionToPoint = PickupTarget.position - currentObject.position;
float distanceToPoint = directionToPoint.magnitude;
currentObject.velocity = directionToPoint * 12 * distanceToPoint;
}
}
private void Update()
{
if (Input.GetKey(KeyCode.E))
{
Ray cameraRay = PlayerCamera.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
if (Physics.Raycast(cameraRay, out RaycastHit HitInfo, PickupRange, layerMask))
{
currentObject = HitInfo.rigidbody;
currentObject.useGravity = false;
}
}
}
}
and this is what happens
guys, quick question. Are these lines something that normally occurs?
well, lines
I can see that they're some sort of gaps that are opening in the tilemap? I'm not sure
you might have an easier time making the object kinematic and moving it via position instead. Otherwise itll always have an issue of possibly getting stuck on something.
As for your current function, currentObject.velocity = directionToPoint * 12 * distanceToPoint; is most definitely wrong, where does 12 come from? and why not just assign it velocity equal to the direction
this is a code channel. but from the looks of it, your tiles are not sliced correctly
maybe you can make it faster ?
sorry, I wouldn't know where else to ask. I'm not sure why that would be. The tiles look alright if I'm not moving the camera and even then, it only happens after a while when moving, randomly
is that yours?
indeed
its just bricks but they're rb , you throw bricks and smash windows
You want to see my script?
welp,ok
then it's likely due to the zoom level in the editor. zoom all the way out in game view and it should look fine. but ask in either #💻┃unity-talk or #🖼️┃2d-tools if you still have trouble
If you do that I will give you credit
you know what i will figure this out tommorow ty for the help
I'll test it out and do that, thanks
no need I stole it from the internet lol
let me get it one sec
private void HoldObject()
{
Ray playerAim = playerCam.GetComponent<Camera>().ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
Vector3 nextPos = playerCam.transform.position + playerAim.direction * distance;
Vector3 currPos = objectHeld.transform.position;
objectHeld.GetComponent<Rigidbody>().velocity = (nextPos - currPos) * 10;
if (Vector3.Distance(objectHeld.transform.position, playerCam.transform.position) > maxDistanceGrab)
{
DropObject();
}
}```
it can probably be cleaned up better(cache that rb/cam) , but I didn't have time to do so
please use links for large code
oh ok
edit the msg with link
Hey uh how do i make 1 player move with WASD and one move with Arrow keys
nvm lol mistead that
best using new Input System tbh
Never used that
if not map each keycodes for each player
hmm
so much for editing your old msg.. one sec
what is even going on here objectHeld.layer.Equals("Pickable")
I know this might not interest you, but just in case, I found a fix to the problem I was having here: https://www.youtube.com/watch?v=Wf98KrAyB2I
I have no clue why it is that way, but it worked perfectly
How to fix tilemap tearing and edges/gaps in a 2D Unity Project is much simpler than you think and does not require reimporting or manipulation of any of your 2D assets, a simple Sprite Atlas is all you need and I'll show you how to do that in under 3 minutes. Tilemaps in a 2D Unity project can be quite frustrating but fixing them is easy. Plea...
can you explain it to me?
to detect if the object has that layer can be grabbed
and who told you this is a good way to check layers?
I thought it was but no
like an example
private void Update()
{
if (Input.GetKey(KeyCode.W))
{
// move Player1 Up
}
if (Input.GetKey(KeyCode.UpArrow))
{
// move Player2 Up
}
}```
oh ok
its not
layers are bitmask not strings
use the struct made for it
LayerMask
besides that, does the code work?
nope 😦
if (objectHeld == null)
{
HoldObject();
}
this makes no sense
why would you hold when its null lol
because if its not it will drop the object
If you don't have anything in your hand you can grab it, if not you will let it go that is 1 slot
grab and holding are 2 different actions
ok,only holding
heres what I had
if (Input.GetButton(GrabButton))
{
if (!isObjectHeld)
{
TryPickObject();
tryPickupObject = true;
}
else
{
HoldObject();
}
}
else if (isObjectHeld)
{
DropObject();
}```
Hey everyone!
I'm currently making a bullet that slows and freezes the enemy whenever he is hit. The idea is that every enemy has a certain frost resistance, and each bullet shot removes that resistance by 1 while also slowing down the enemy for an x amount of time. When the frost resistance reaches 0, the enemy is frozen for an x amount of time.
I have the functionality basically working, but I can't figure out how I can extend the slow if the enemy is hit by a bullet before the last slow has run out. Since I'm using coroutines, it seems like the next coroutine doesn't get updated information from the last coroutine, so it only ever knows if the slow has already ended.
I would appreciate any help on how I could extend the slow by another x number of seconds when the enemy is hit before the slow has ended.
The game is 2D btw.
Here's the code:
https://pastebin.com/iXqPDbLB
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.
dont you have the complete script?
im getting dizzy
Mine is mostly modified to fit my needs
I think it was this :
https://cdn.twgamesdev.com/tutorials/DragRigidbodyUse.cs
maybe was this video
https://youtu.be/CcUfxm_ZabM
ok,i love you 😘
hey there, can somebody help me a bit since I'm having trouble with raycasts? I'm never getting any hit information for some reason and I'm dumb. imma send the code in a sec
Alright so I’m getting “The result of the expression is always ‘true’ since a value of type ‘OVRInput.Button’ is never equal to ‘null’ of type ‘OVRInput.Button?’”
When using “if (x.xInput != null)” How do I fix this?
x.xInput is a variable of a value type that is not nullable so it will never be equal to null. why are you trying to check it for null?
This is an asset that’s free on itch, but it’s old and the discord isn’t active so I can’t get support
so it's not even your code?
No
then ignore it. it's just a warning anyway
But it stops some things from working
it just means that statement will always be true, it's the equivalent of if(true)
i doubt that
Oh well maybe I’m just dumb lol
it takes from another script that is just used to get the navmeshagent and the animator components
that's not related though
the raycast never actually hits anything, even though I've made sure it's pointing the right way with a debug ray and there's also a bunch of other objects in between the one casting the ray and the target
it's also using a layer mask with all of the map and the target selected, without the parent object so it doesn't collide with itself
the ray shows that the direction is correct on this screenshot
(the white lines are the camera , the capsule is the player and the target)
what collider are you expecting it to hit and does that collider exist on a layer that is included in your layermask?
yeah, the walls are in the map layer and the capsule is in the player layer
I just realized testing now, apparently the ray is too low
when I jump on top of the thing it does register
well your raycast originates at the transform.position which is at the feet of your object (as shown by your previous screenshot)
uhh how do I offset the ray origin a bit on the y axis? I'm so dumb sorry
wrong chat im sorry
Make sure to delete your messages #💻┃code-beginner message
add another vector3 to the transform.position where the vector3 is the offset. or create an empty gameobject where you want the ray to originate and reference that
oh also, you do know that awake() is never called, right?
Are you wanting to offset the direction as well?
var origin = transform.position + offset;
var direction = (target.position - origin).normalized;```
Reminder that awake isn't the same as Awake
I have a teleport script that worked, but when I updated untiy it caused it to stop working. When I try and teleport now it will take me to the location for a split second than take me back to the og postion.
I am not a beginner in unity programming but I am in physics and that kinnd of thing so I think here is best. I am creating my own custom modular movement system and im working on my jump module currently. Here is my code
public class JumpModule : MonoBehaviour
{
public bool isEnabled = true;
public MovementManager movementManager;
[Header("Customize")] public float jumpForce;
public int maxJumps;
public float jumpCooldown;
private int jumpsRemaining;
private float lastJumpTime = 0.0f;
private bool isJumping = false; // Track if the player is currently jumping.
public void StartJump(InputAction.CallbackContext context)
{
if (!isEnabled)
{
// Disable the script immediately if isEnabled is false
enabled = false;
}
else if (jumpsRemaining > 0 && Time.time - lastJumpTime >= jumpCooldown && !isJumping)
{
// Call your custom logic method when isEnabled is true, there are jumps remaining,
// the jump cooldown has elapsed, and the player is not already jumping
Jump();
}
}
public void Jump()
{
if (jumpsRemaining > 0)
{
movementManager.rb.velocity = new Vector3(movementManager.rb.velocity.x, 0.0f, movementManager.rb.velocity.z); // Reset vertical velocity.
movementManager.rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
jumpsRemaining--;
}
lastJumpTime = Time.time;
}
public void Start()
{
jumpsRemaining = maxJumps;
}
public void Update()
{
if (movementManager.isGrounded)
{
jumpsRemaining = maxJumps;
}
Debug.Log(jumpsRemaining);
}
}
In the update method I am setting the current amount of jumps I have to the max amount so it resets my jumps. The issue is that when I jump the first time I am grounded and so it immeditley resets the max jumps.
are you sure you aren't teleporting it back? or are you perhaps teleporting a CharacterController? either way though you should see #854851968446365696 for what to include when asking for help
Something physics related should really be done in FixedUpdate
This will avoid that kind of problem
You should also delay the force until FixedUpdate as well
https://hatebin.com/quzsddmqfj
I am using a CharacterController for my player
you should also have a way to tell the movementManager that it is no longer grounded when you start the jump
This did not work but I did not know I should use fixed update. Thanks!
I dont really have a need for that though. Because the movement manager knows the player is in the air with a raycast.
okay then you're going to continue being considered grounded until at least one frame has passed and the movementManager can update its own grounding status
Even if I tell the movement manager that the player is in the air with jumping im still going to have the same issue because checking if the player is on the ground is run on update so the movement manager already knows the player is on the ground.
if you tell the movementManager that it is no longer grounded, then why would it be grounded when you check later that same frame?
Because im not checking later on that frame, I would be checking on the same frame that i would tell the movement manager.
the same frame
later on that frame
that's the same thing
Correct me if im wrong but thge movement manager would not be able to update in time before the player jumps.
what? just tell the movementManager that it is no longer grounded when you jump. then you will no longer be considered grounded until the movementManager checks for ground again. it's not that hard
I agree that it's not very complicated, but the problem seems to be that you might not fully grasp what I'm trying to convey. Here's how my jumping mechanism functions:
Every frame, it checks if the player is currently on the ground. If they are, it resets the number of jumps available.
When the player attempts to jump, it checks whether they have any remaining jumps left. If they do, it applies the jump forces.
However, there's an issue when the player is on the ground and tries to jump. In this situation, the remaining jumps don't decrease after the first jump because the player is still considered to be on the ground, which resets the jump count. If I were to inform the movement manager that the player is no longer on the ground, this information would be immediately overwritten by the update function, which reports that the player is still on the ground.
so you know that you need to not be considered grounded. you also know that your movementManager checks for ground every frame (which is basically pointless, just do it on FixedUpdates since you are moving via physics anyway).
you were instructed to inform the movementManager that it is no longer grounded. knowing that it will check for ground again in that same frame, would the obvious solution not be to simply not check for ground in frames that it was told by outside sources that it is no longer grounded?
the player is still considered to be on the ground
This is because you're doing the jump itself in the input callback rather than in FixedUpdate as suggested
You say you tried it but I'd like to see your try
Another missing piece here is how movementManager.isGrounded is calculated
because that may also be problematic
This is my update now for my is grounded
public void FixedUpdate()
{
if (movementManager.isGrounded)
{
jumpsRemaining = maxJumps;
}
Debug.Log(jumpsRemaining);
}
this is my calculation for grounding
void FixedUpdate()
{
// Cast a ray from the center of the player's position downward to check for the ground.
RaycastHit hit;
if (Physics.Raycast(transform.position, Vector3.down, out hit, groundCheckLength, groundLayer))
{
isGrounded = true;
}
else
{
isGrounded = false;
}
}
also for what boxfriend said is exactly what I want to acheive, which is not heck for ground in frames but I genuinely cannot think of a simple way to do this.
you've heard of if statements, right?
now you have an awkward execution order issue between the two scripts. You should probably just make IsGrounded() a function or a property and do the raycast on demand
Yeah now I know how to do it after thinking about it for a sec.
you should still take Praetor's advice though about making an IsGrounded method so you can ground check on demand instead of a potential execution order issue.
but you can also do exactly what I suggested too where your IsGrounded method can just return false if you ungrounded the object that frame. (you'd just need to make sure to reset whatever bool you are using either at the end of the frame or during the next one
Anyone got advice on this?
instead of using a WaitForSeconds you could create your own timer using deltaTime and yield return null, then just add to the current duration
My advice is that coroutines are probably not a good idea for this
I'd probably do something like:
Queue<float> freezeCharges = new(); // keeps track of the time at which freeze charges were applied.
public void HitWithFreeze() {
freezeCharges.Enqueue(Time.time + freezeDuration);
}
void Update() {
// get rid of expired freeze charges
while (freezeCharges.Count > 0) {
float nextExpiration = freezeCharges.Peek();
if (Time.time >= nextExpiration) {
freezeCharges.Dequeue(); // the charge has expired
}
else {
break; // we're done. The next expiration time hasn't come yet.
}
}
if (freezeCharges.Count > 0) {
// use slow speed
}
else {
// use normal speed
}
}```
Interesting, looks pretty good, I'll try it out
I guess I just have to drop the coroutines
https://hatebin.com/oykiqzmuqb How do I make my 2D asteroid object which moves straight to the left Rotate on the Z axis slowly without it disturbing the movements direction? I used many rotates but they always mess up the asteroids movement left path?
you've got a potentially infinite loop here. but would this not be basically the same as just setting a float to Time.time + freezeDuration and just using the slow speed until Time.time has passed that? the queue seems pretty unnecessary here
ah wait, discord formatting kind of fucked up that if else. no infinite loop
Your first statement might be correct
the only reason we need the queue is if you wish to display the number of freeze charges in the UI
or really, if you need the actual number of charges for any reason
if you just want to know when you're at zero (which currently seems to be the implementation), then yeah there's no need to track the number of charges and you can just use an "unfreeze at" time
ideally you wouldn't be moving the object via transform.Translate and would instead move it with its Rigidbody2D. you could easily just assign its velocity to the same thing you are using in Translate (but without the deltaTime multiplication). otherwise you could use the optional second parameter for the Translate method to move it in world space
Yeah I changed the movement to rb.velocity
Wooooo my asteroids are spinning!
Thanks a lot
Ok I ended up doing this before dropping the coroutines and looks like I got something working
What’s the best way to learn C# for unity that helped y’all the most?
Just now learning about a month ago.
there are beginner c# courses pinned in this channel. though I personally recommend the book The C# Player's Guide by RB Whitaker. it's a great resource for learning c# in a decently gameified way
additionally what helped me most was making various Console Applications.
its very fast to save / compile / test code right away
@slender nymph @rich adder thank you!
I’ve been watching brackeys beginner course and a couple others.
Was debating on a good book but get mixed views.
Want to mainly use c# for gaming of course but would love to learn in full in the end.
brackys is the worst for c#
I would be cautious with Brackeys
@rich adder @slender nymph
Okay thank you. Brackeys was the only one I knew off top.
My current course is by learn, play, create
i have a scirpt that references a bool from a diff script but i cant drag and drop the script into the feild in the inspector
Are you dragging it from a scene object to a prefab
Is the script you need a bool from attatched to a gameobject or is it standalone?
https://unity.huh.how/programming/references
This is a good guide btw
no im draging it from my scripts folder to a scene object also i tried to drag an empty that had the script on it and it went in but it didnt do what its supposed to
Ok, can't do the script, but can do the object. You need an INSTANCE to reference. How did it not do what it's supposed to do?
You can't reference a script itself in the unity editor (unless it's attatched to something) if you want to reference a script itself, the class needs to be static, and the bool needs to be public
its a destroy script so if the bool im referencing is true that it will destroy game object but its not
Ok, probably just an issue with the !code then. Show that
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
For example:
public class myClass
{
public static bool PossiblyDestroyObject(parameters)
{
logic
...
return shouldDestroy (where shouldDestroy is a bool);
}
}
You can then call this function by doing:
bool shouldDestroy = myClass.PossiblyDestroyObject(insert parameters);
^^
ok so I the after fixing the raycasting there was a new problem and this one is truly weird at least for me
so I have this character that's basically a capsule that's on his scene and he can move and jump and everything
but when I move it to another scene the jump refuses to work, it either doesn't jump or jumps but continues to go up infinitely
imma post the code for the movement script in a sec, but it shouldn't really change with the scenes
it was writter (probably stolen) by a friend so I don't 100% understand it and can't tell what's causing the issues
did you check console for any runtime errors?
no errors
also taking the character from another scene was needed because on the one I'm working it just broke after changing the layer from layer 8 (map) to 9 (player)
idk why my friend had it set up that way but I needed to change it to use a raycast layer mask
and changing the layer also breaks it on the scene where I'm taking it from
I honestly have no idea what could cause this
Read the code.
Start from the end of the issue.
Since it's related to movement, check the movement vector you pass into _controller.Move. It probably has a vertical velocity.
After confirming it, break it down and see where that vertical velocity is coming from.
might def be issue with layers then
Debug with a breakpoint ot logs to see the values.
yeah that's the actual problem most likely
alright, apparently the sphere to check whether it's on the ground or not is having a stroke and detecting other parts of the character
those parts are probably part of the checklayers
can you use layer masks for sphere checks as in raycasts?
yes you can use layermask
that should save me the trouble of having to change it too much
all right it now works
now I gotta copy it over to the other scene and pray
thanks guys
How woukd I learn to code with the Unity engine?
- Learn to code with C#
- Learn unity API and workflow
There are resources pinned to this channel
Say I have a vector3 point in world space and an array of 8 corners of a 3d shape also in world space. Is there an easier way of determining whether the point is inside those spaces than calculating all 6 planes? This is what I currently have but it doesnt seem to be returning true for points that certainly lie within the shape
{
// Check if the frustumCorners array has the expected length (8 corners)
if (frustumCorners.Length != 8)
{
Debug.LogError("Invalid frustumCorners array length.");
return false;
}
// Define the six planes that make up the frustum
Plane[] frustumPlanes = new Plane[6];
// Calculate the frustum planes using the corners
for (int i = 0; i < 6; i++)
{
Vector3 a = frustumCorners[i];
Vector3 b = frustumCorners[i + 1];
Vector3 c = frustumCorners[i + 2];
frustumPlanes[i] = new Plane(a, b, c);
}
// Check if the point is in front of all six planes
for (int i = 0; i < 6; i++)
{
if (frustumPlanes[i].GetDistanceToPoint(point) < 0)
{
// The point is behind this plane, so it's outside the frustum
Debug.Log("Not in frustum");
return false;
}
}
// If the point is in front of all six planes, it's inside the frustum
Debug.Log("Is in frustum");
return true;
}```
I have a feeling its due to the order of the points, should I go be going clockwise front to back?
i may consider using normal and dot product for testing
btw your vertices is unordered, no way to construct the 6 planes
Is this for a camera frustum?
there's some utility library for that, but perhaps it could be used for this problem too
I wish, virtual camera frustum (no camera component)
Let's explore how you can detect when an object is inside the players camera view by using the camera's frustum and axis-aligned bounding boxes (AABB). This takes advantage of Unity's built in GeometryUtility class that provides some helper functions to make this easier.
The fi...
https://docs.unity3d.com/ScriptReference/GeometryUtility.html
seems to be the tools they are using
Oh this should still work, I'll take a look and try wrap my head around it further
btw, thanks for the heads up on this, now im only allocating 1 string instead of like, 3-5
so, im getting a weird issue, where whenever i boot up my unity project and run it, the logic for my game manager goes wonky
like, it will work perfectly yesterday, and then when i boot it up for the day to work on my project, the logic will break
and it doesn't fix itself until i go ahead and delete the and reinsert the script into the scene
Okay and now it's doing it everytime i reboot unity, instead of when i reboot my PC?
what is going on with my script??
Are you using git? If so, are you seeing any differences coming up to commit?
i do use git but i haven't done any commit in a while, none of my scripts are being reverted or anything
I do use git, and yes i do see differences to commit
i haven't commited anything in about 2 months tho
Ah, it might be hard to tell if it's not commited for so long, I was thinking commit when it works, and see if any changes occur that would make it obvious what broke it.
That's a long time to go without commiting haha
its because i took a break from the project and only hopped back into Blender recently to finish making the first level, and then taking it into unity to set it all up
Oooh, fair. I had assumed there were a lot of built up changes.
what's weird is that it seems the script only breaks in the new scene i made for the first level, it doesn't break in the testing/sample scene i made to code up the game logic and stuff
and as i said, the script works when i delete it out of the scene, and then reinsert it back into the scene
Ahhh ok. Are you directly entering the scene in the editor (by double clicking or whatever), or is it from a LoadScene call?
And yeah, that part is pretty interesting. I might just need more details. What exactly do you mean by "logic breaks" and what does it do when it works?
so basically, the part that's break specifically is the gun inventory of my game
i am directly entering the scene from the editor, there's no title screen or level select or anything like that atm in my game
I am almost finished with my basic AI
that is due tomorrow !!!!
I had to redo the whole script because my friends are dumb
anyways does anybody know how do I stop a collider from bumping into things? if I can do that then the only thing left will be the animations which are not my job
if I set it to trigger then it stops registering other colliders but if I don't then it just bumps into everything
what do you mean bumping into things? That is simply a collision right? If you mean specific things, you can configure the collision matrix so, for example, it only collides with the ground?
If you want it to "register" other colliders (do you mean recieve physics messages like OnCollisionEnter?), they will also need to "bump into" things
if you do a trigger, you can get the OnTriggerEnter message if you'd rather, but you'd also fall through the ground of course.
I mean the character has a big collider used to detect the player, but it is stopping him from navigating since the collider gets stuck with walls and even the player itself
shouldn't different colliders be able to overlap?
Make the collider a capsule and make it smaller
A non-trigger collider should be roughly the same shape and size as the modle
No, of course not. They are supposed to collide
basically, i have 8 guns in my game, and the way the game manager keeps track of what the player has or doesn't have is to initialize an array of 8 bools that represent each gun (true = have, false = no have)
basically, in edit mode, i set the initial "starting" weapon by enabling it's view model on my player, and then when i enter play mode, my Player script first sees which weapon in the viewModel list is enabled, and sets that as the Current Gun. It then enables all of the viewModels to wake up all of the guns' scripts so that my game can keep track of their ammo counts. Is then disables all the weapons, and only reenables what's supposed to be the current gun. The player script then calls upon the game manager to add the starting weapon to the list of 8 bools by setting the current gun's corresponding index in that list to true. In the Game Manager's script, when i first enter play mode, it just adds 8 false bools to populate the list. The bug im having (and the part of the logic that is breaking) is that the player script is not able to properly read the GameManger's gun list or something, and when it tries to Add the default weapon to the gun inventory, it just sees an empty list, and the method fails. This doens't crash the game, only leads to the undesired behavoir of being able to switch forward (but not backward, for some reason...) only between the first and last weapons of the total gun list.
@summer stump That's the best way i can describe how my weapon system works atm, it's confusing i know, but it works!... at least until now
THAT collider looks like it's supposed to be a trigger. You would ALSO want a non-trigger collider (a capsule sized properly like I said)
at this point it might as well just be easier to use raycasts for what I want to do honestly
Hmm ok. Have you used the debugger? I would put in some breakpoints to check the values at runtime. Or at least do some Debug.Logs to tell you state of the array.
I can't say much more without seeing the code
yeah, i had debugs in my code, but for some reason i removed em because the bug went away
Raycasts are great for sure, you should definitely use them IN CONJUNCTION with a collider.
Is your rigidbody kinematic, or do you even have one? If you have one and it's not kinematic, you'll need a collider. or you'll just fall through the ground
I mean, a collider is gonna just... do the work for you. Otherwise you need to write a ton of code to get the raycasts to work with not walking through walls and stuff.
now that it's back i gotta find out where the hell i put the debug logs, lol
Probably in the place you try to add the weapon. You debug the array right then, and then maybe ALSO right after
I do have a rigidbody and it's not kinematic
Then you absolutely want a collider
You don't have a character controller on it do you? Those contain a collider already, and shouldn't be on the same object as a rigidbody.
Just checking.
nope
I can give him two colliders so that he doesn't run into walls, the main problem is still there
oh wait I forgot to tell
the character with the big hitbox is the one checking for collisions and not the player
maybe I should give the big hitbox to the player now that I think about it
Only do two colliders if the big one is a trigger. The actual non-trigger collider should be as close to the size of the model as possible. Otherwise you get stuck when navigating and bumb into things far away, haha
@summer stump found my issue, for some reason, when i load the scene in the editor, it makes it so that the player script awakens first, before the gameMananger awakes and sets up the array of Bools. Basically when i try to add my defaultGun, it's accessing an empty array because the array hasn't been initialized yet
for some reason, loading the scene messes with the boot order of my object it seems
and the boot order gets "corrected" when i delete and reinsert my game manager script
Ahh yeah. So, one thing to keep in mind is that the order of awake will be kinda random for objects already in the scene when it loads. HOWEVER, ALL awakes will run before ANY start (again, for objects already in the scene). So you should do self-references and building in Awake, and reference OTHER objects in Start
a dumb fix would be to deactivate the player in the editor and activate him on the void awake of the gamemanager
hmmm, weird, i get it's random, but how come this issue is only popping up now?
this project is a year old (i know, long for a "test" project but im learning, okay?) and always had more than 1 scene
I'm not sure honestly 😂
It's a pretty common issue, which is why that self-reference in awake, other reference in start is such a big rule
how come now the execution order is all jumbled?
i see, alright
so the solution is to move my gamemanager stuff from awake to Start on my player script
well at least im learning this now
before things got really complicated
How it decides which awake to call in which order is beyond my knowledge lol. I'm sure someone else could answer
The execution order of each event type like Awake is not guaranteed unless the script is explicitly put in the order list https://docs.unity3d.com/Manual/class-MonoManager.html
soo all this time, before i started working on my first level scene, i've just been lucky as hell that my script never exploded like this
damn
You probably added more scripts that made the order more random
Note Awake will always be called before Start its two of the same type that are not guaranteed unless you specify it
So Awake from script A might run before Awake from Script B
Or it could happen the other way around
player script should probably be start while the gamemanager should usually be awake
anything non-dependent in awake
ok so remember when I said that the trigger colliders weren't working? I was dumb
I use a OnCollisionEnter instead of an OnTriggerEnter
that just goes to prove how dumb I am
ok, i see, thanks for the help guys, i appreciate it alot
@timber tide @charred spoke @summer stump You have expanded my Unity Knowledge

my code would've worked like an hour ago if not for this
Ah, I mentioned that, but it was in the middle of a bunch of suggestions and questions. I have such a bad habit of shoveling too much at once on people haha. Glad you got it!
thanks
yup, changing non-dependent calls to start() fixed it
yay
whew, that was making me pull hair a bit i won't lie
very fast ask here, how do I compare the contents of an array to another array?
I forgot how to do it
void CompareMyFlags()
{
string[] arrayOfPossibleFlagsReached = flagContainer.possibleFlagsReached.ToArray();
if (arrayOfPossibleFlagsReached.Length == 0)
Debug.LogError("There's nothing to scan, chief!");
for (int i = 0; i < arrayOfPossibleFlagsReached.Length; i++)
{
for (int j = 0; j < flagContainer.allMyFlags.Length; j++)
{
Debug.Log(flagContainer.allMyFlags.ToString());
//if i==j, break
while(flagContainer.allMyFlags != arrayOfPossibleFlagsReached)
{
Debug.Log("");
break;
}
}```
kinda hard to understand the code since most of the variables arent shown, but you dont need 2 for loops here. if you are just comparing both arrays, you want to run through both once (and its up to you for what you want to do if they are different lengths).
Just store the length of one array, then run through both like arrayOfPossibleFlagsReached[i] and flagContainer.allMyFlags[i]
I'm looking for the specific value
So... each string must match up exactly
Like the flag system is used to mark if quests are finished or not
so my system needs to look for eg. 'Egg' in the allMyFlags and compare it to arrayOfPossibleFlagsReached for the value of 'Egg'
do yall think this loading bar will ever complete or will I have to redo the last 3 hours because I haven't saved in a while?
Let me show the whole code here
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 might as well say goodbye to my code now
it doesnt really sound like you need to use both arrays in this case, im not sure what you would even be comparing it for. one has all flags, and another is the flags reached. All flags sounds like it holds every single one, so the only thing you'd be searching for is the index.
Although there is probably way more to this than just "compare contents in arrays" because i dont know what you intend to do with this
"compare" is a very general term
your scene might be unsaved but stored in the temp file (google that). dont reopen unity before getting the temp scene. your code files still will be saved.
Remove all the unnecessary white space to make the code shorter, and put C# as the language to add syntax highlighting and make it readable . . .
beyond fucked
It triggers and ties into an event system.
Event system sends call to add entry to myFlags array in the SO, or compare both arrays together.
AllPossibleFlags reached stores all flags in the chapter on a SO. Myflags is what flags have been reached and stored by the player. Upon reaching a 'gateway', the flagChecker is supposed to recieve a call from Event system. It will scan the myFlags array for all possible flags and compare them to the flags in allPossibleFlags.
Once it finds a match, it will trigger the appropriate event.
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.
this?
yes, you can just change the name and then check if its more recent than whats saved inside unity. your code though is unrelated and will have been saved already by you
I'm debating on using a dictionary for this, but I don't think you can add to dictionaries like you do to arrays, right?
dictionary or hashset supports o(1) add,remove and lookup
im honestly unsure where this even ties into any of what you've described but having a string array to later invoke some events is questionable. if ive understood what you are describing
ok something has to be causing this imma undo some bits of code
at least I do have the scene
Why so?
string based anything is always gonna be fragile
true
is there something against while loops ? that seems to be the cause of the bug
although i still dont know what you're actually trying to compare
What's a more robust system? I'm wondering if dictonaries will be less prone to corruption but IME they're super hard to add too and remove.
Basically comparing if A = B at certain points. If they are, trigger scene C. If not, trigger scene D
That's the gist of it
Or
If (A = B && C = D)
{Scene E}
Are you calling this while in update?
can have multiple flags that are compared or just 1
Although it's got pretty huge potential to get messy so I'm trying to build good framewor
yes and no
Yes and no?
the condition is always true, meaning remainingDistance is never greater than 3. Its not about the while loop but more about there are conditions when your loop will never stop
and then wait a bit
there are four possible destinations , the chances of the distance being greater than 3 are 3/4 every time, it shouldn't be always true
im honestly having trouble understanding what this is actually for so im not sure what to suggest. it seems like you might benefit from using a bitmask with what you described "If (A = B && C = D) {Scene E}"
but this is just a longshot because i really dont know whats going on here
Okey so same thing. Think about what is happening. A while will repeat the code inside it WHILE the condition is true. So your agent is <3d from his destination you set a new destination then it goes to the check again and it is still <3f the game has not progressed. FixedUpdate is already a kind if while loop so you dont need it just change the while to a if
So basically like I'm most RPGs they have a quest system that determines if you've completed certain objectives and have certain items in your inventory before you can go to the next stage?
That.
I'm essentially making a system that checks if you have item A, B and C, before you can progress to area D. If not, you go to area E.
?
You add and remove to a dictionary just like a list. Provide a key to assign a value. Though, I do not understand why you convert to an array or what the comparison is for . . .
it doesnt really make sense what you are comparing the 2 arrays for, like you have A in one array and are trying to find it in the other?
the thing is, that part of the fixedupdate runs only once and then waits a bit until the character gets to the destination and a set amount of time passes. if I just use a if it will have a 1 in 4 chance of just staying in the same place every time it should change destinations
and I'm trying to look for A in myFlags
eventually it would get out of there but I will need to use longer wait times on the destinations so if it was there for 40 seconds I wouldn't want it to be there for another 50
and maybe even a third time if my luck sucks
I had to convert the list to an array because I don't think there is a way to compare lists to arrays
why are you compare list to array, you want to compare the element in array to element in list
I'm not
I'm converting the list into a format where I can compare it to the array
They are both collections. You just iterate and compare the elements (items) of each collection, not the collections themselves . . .
You can access a list the exact same way as an array
The conversion is unnecessary . . .
Won't that be pretty expensive to .ToString everything inside the array whenever a check is called? Is it possible to do the same using a dictionary where I just compare the keys?
So convert both ```cs
public List<string> possibleFlagsReached = new List<string>();
public string[] allMyFlags;```
To a dictionary
idk why you call tostring in string actually...
You have a list of string and a string array, you dont need to convert a string to string
But I'm not sure how I would handle adding flags to the dictionaries. See, flags are added to the allMyFlags depending on certain actions the player takes... I don't know if it's possible to add and minus from a dictionary in such a way.
imma just go to sleep since it's almost 5am
you can remove key from dictionary ....
Both collections are of type string, not sure why you use ToString to begin with . . .
It wasn't possible to get a debuglog of the array unless I did a .tostring
You should probably look at the basics of c# first because honestly this approach seems very fragile/unnecessary. Maybe due to not being experienced with collections
I have lol
I am using an events systems
do you know how to get array element?
It's just not implemented yet, I'm trying to make this thing work
Yes
I know it's fragile but there aren't that many other ways due to time constraints
i don't have a year to relearn C#
Itd probably be easier for all these flags to just be bools somewhere. Or a bitmask
I need to get something reasonably functional out the door by the end of this year
Yeah the original idea was using a dictionary and a hex value to refer to each flag
but I don't think it's very agile because I have trouble calling the dictionary
Mess around with a dictionary outside of unity. It's very easy to use. Although I dont know what you plan to use the dictionary for either
Like the key would be the flag name then the value would be if they completed this objective?
Something Like
'0001DOOR' == true/false
'0002ROOM' == true/false
Yeap
So either I store all the values per chapter in a dictionary on the scriptable object, then on the correct event, the event manager pings the dictionary to change the bool value
Wait uh, I think this seems like a pretty good solution
That would at least get rid of the 2 arrays existing
Just scan the dictionary for '0001DOOR' == true and '0002ROOM' == false at the relavant checkpoint
ok thanks
I think
this actually solved quite a bit of the problem
You dont need to "scan" the dictionary, it has a O(1) lookup meaning its constant time
Yes, that is the concept of using the dictionary instead . . .
Like I said a while loop repeats until its condition is not true. It stops all other code from running. Yes you set a new destination, but the code in the agent responsible for calculating the new remaining distance cant run since you immediately loop back to check the old remaining distance. You have created a infinite loop
This just means you access it directly if you know what you want to access
true
So I'll just need to access several keys in the dictionary at relavant points
and check if the bools are true
if true, play scene D
if false, play scene E
There is going to have to be somewhere that you define what a quest is, and thatll probably be your string array then to lookup elements in the dictionary. That part might still be fragile but honestly you could just throw all the strings in a file then reference it by variable name.
I'm just wondering if it's possible to turn a dictionary into a SO where each chapter contains a seperate data set, or a dictionary spans all chapters?
Like, a SO for just chapter 1 flags, chapter 2 flags... etc.
You are gonna have to construct the dictionary from some data, if that data is stored in an SO that's fine. The SO can be used to just create your quests, where you store the flags you want completed on them
If that's what you're asking
i see
sorry, I'm tired as fuck and completely misread your other message
so all dictionary data will encompass the whole game?
cant split it up into multiple scriptable objs?
You'd create an SO containing a list of flags for each chapter, then populate the dictionary during runtime using the list, or use a custom editor for a dictionary to use it directly in the SO instead . . .
Depends how you want to do it, you could have many small dictionaries or 1 massive one
i see
It shouldnt really matter, but if you have a small dictionary only containing the exact same thing as 1 list then you likely dont need a dictionary
You could just add to a counter at that point and check if the counter equals the list length
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
how can transform have a reference to the gameobject and vice versa? wouldn't that lead to a circular reference?
the game object its assigned to?
Yes it does, and no it's not a problem
idk whats wrong
storeData:https://hatebin.com/dkfgjytaoi
saveData: https://hatebin.com/ruvqfoylcv
yes
you shouldnt use BinaryFormatter in the first place
i thought an exception usually happens, or it won't let you compile
nope
storeData 11 line "this" have red outline
so having a circular reference isn't a problem at all?
correct
thanks, i remember got a circular reference error when doing web dev so i thought it'd be the same here too
I mean it can be a problem in some situations like serialization, but as a general concept no
yeah i thought having circular references is not possible that's why i asked
why it is not possible.....it is just a graph with cycle, and requires guard on serialization to avoid visiting same vertex twice
i fixed myself
are you using Binary Formatter?
yup
(i watched random youtube tutorial lol)
It's tagged as insecure and untrusted by microsoft
and shouldn't be used for new projects
you can still use it, but everyone will say that you shouldnt...
Or rather consider that arbitrary code can be injected into it, malware for example, and executed at runtime.
is that why BF is unsafe?
yes
thats why most games just use databases to save data
... or use a safe binary serialization option like Binary Writer
There are custom fast binary serializers as well, like this one https://github.com/Cysharp/MemoryPack#unity
thx
i will not use binary formater on data cuz i want to make secret ending what can be found only by editing game data
it has a limit
if you want easy readable save you can use NewtonsofJson which is used by unity internally as well
yea, probably because of the .net features supported it uses
yep
Hey how can I reference to this?
But yea, for json install this package, can be installed just by name https://docs.unity3d.com/Packages/com.unity.nuget.newtonsoft-json@3.0/manual/index.html
Drag into timeline object type reference, I guess that what it is?
Well, but what is it? A PlayableDirector?
I can reference to it as a playable asset tho
You should be able to see in the inspector what that is
Another way would be to drag-drop it into a field of type Object, call .GetType() on it, and log the result
or lookup in the manual
https://docs.unity3d.com/Packages/com.unity.timeline@1.8/manual/insp-tl-asset.html
Switch to Scripting API to see properties, etc.
Thanks, timeline asset
Could someone assist me with my 3rd person camera? The camera does not rotate vertically and my attempts to fix it cause the camera to get lopsided.
public static float rotationX = 0;
public static Vector2 rotationLimits = new Vector2(80, -80); // Vertical rotation limits
private static Vector3 offset = new Vector3(0f,0f,0f);
void RotateCamera4(float x, float y)
{
Transform target = Object.PlayersMainObject[0].GameObject.transform; // It's just a GameObjects Transform.
// Get the mouse input
float mouseX = x * 2f;
float mouseY = y * 2f;
// Rotate the target horizontally
Camera.main.transform.Rotate(Vector3.up * mouseX);
// Rotate the camera vertically
rotationX -= mouseY;
rotationX = Mathf.Clamp(rotationX, rotationLimits.y, rotationLimits.x);
Camera.main.transform.Rotate(Vector3.left * mouseY); // My attempt
// Calculate the rotation quaternion
Quaternion rotation = Quaternion.Euler(rotationX, target.eulerAngles.y, 0);
// Calculate the new position of the camera based on the rotation and offset
Vector3 newPosition = target.position + rotation * offset;
// Apply the new position to the camera
Camera.main.transform.position = newPosition;
// Make the camera look at the target
Camera.main.transform.LookAt(target);
}```
This is attached to my Sniper weapon prefab which has a chance of spawning when killing an enemy. The "Camera Zoom" is attached to my main camera. Is there a way to automatically access the Camera zoom when the prefab spawns? I thought this would of worked but it doesnt
This is my error and I'm struggling to figure it out
First off, why are you not using #🎥┃cinemachine? It's really good for camera's.
Secondly, you are rotating your camera manually first, and the you do a LookAt with your camera. Isn't that kind of pointless? The LookAt will overwrite anything you rotated manually.
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
And the code that you made 😄
My guess is that you are doing something weird with brackets.
I honestly don't really know how to do camera code at all. I got this code from ChatGBT and modified it.
I can certainly switch to using Cinemachine but I like to do a simple code first to understand.
GetComponent looks for the component on the object that this script is on
Yeah ChatGPT just copies the most popular thing, even if its wrong and tells new people that this is the way to go with full confidence. That's kind of the problem of using ChatGPT as a beginner.
Since Camera zoom is on your camera, get a reference to your camera first then GetComponent on that
makes sense. Forgot that Getcomponent only accesses the object the script is on
You should check the pins for the link on referring to members on other scripts
Can you point me in the right direction? My biggest problem is the code-math which I don't understand maths at this level.
Anyhow, my suggestion is to use the Junior programming pathway pinned in the top right to learn actual coding.
Thank you. I know the solution. just had a bad moment :p
These need to match
Sorry maybe I misspoke, I can code in C# I just don't know or understand the maths used for a camera.
oh that's why
can someone help me with this? i'm trying to spawn these cubes in a plane, but the code i found seems to not work correctly? i'm spawning about 300 green and 300 red cubes just to test, but they seem concentrated on those spots, is this normal ? do i have to code in logic that spreads them?
here's the code ```csharp
public void SpawnCollectables(int number, GameObject plane)
{
var planeMeshRenderer = plane.GetComponent<MeshRenderer>();
var SpinningBoxScript = SpinningBoxPrefab.GetComponent<SpinningBox>();
float x_dim = planeMeshRenderer.bounds.size.x;
float z_dim = planeMeshRenderer.bounds.size.z;
x_dim /= 2;
z_dim /= 2;
SpinningBoxScript.material = CollectableMaterial;
SpinningBoxScript.Type = "Collectable";
for (int i = 0; i < number; i++)
{
SpawnSpinningBoxAtRandomPosition(plane, x_dim,z_dim);
}
}
private void SpawnSpinningBoxAtRandomPosition(GameObject plane, float x_dim,float z_dim)
{
GameObject obj = Instantiate(SpinningBoxPrefab, UnityEngine.Vector3.zero, UnityEngine.Quaternion.identity, plane.transform) as GameObject;
var x_rand = Random.Range(-x_dim, x_dim);
var z_rand = Random.Range(-z_dim, z_dim);
z_rand = x_rand > z_rand ? Random.Range(0, z_rand) : Random.Range(0, x_rand);
obj.transform.position = new Vector3(x_rand, BoxHeight, z_rand);
}
ok, changed it
Well I'm sorry, I don't see anything valid in that code, getting the target that way is strange, using the mouse input that way is strange, rotating that way is strange. There is nothing I can do here, in #💻┃unity-talk there is a 3d person controller pinned in the top right you can freely download and you can look at that perhaps.
No problem. Thank you for even trying! I'll look into CineMachine and the #💻┃unity-talk thing. THANKS!
@fossil drum i solved it but ty
How do I hide an inherited variable on the inspector from the subclass, but let it show on the base class?
I.E hide this
But show this
With a custom inspector for the subclass

@fossil drum You're right, cinemachine makes things so much easier. I got my camera to work fine now.
Are there 2D versions of the navmesh agents for pathfinding?
please where do I go to ask about a bad baking result
ok, tnks
apparently if you destroy things in a grid layout group, on mouse down doesnt work on them but on mouse enter does???
does anyone know why this happens?
if you set the parent so something else it works fine; if you add a crad it wroks fine but destroying them directly does some wierd stuff for no reason
if you need to see my scripts i can show you them and gie an example of what i mean
What is the easiest/simplest way to implement a basic save system in Unity that works on mobile and PC?
I just need to save a JSON format ideally, but anything else works.
it's just some numbers(indexes from array and "levels" or "gold/currency")
It has to work with multiple save slots, but I think that is no issue once the basic system is in place.
Integrated JsonUtility can do basic serialization
There's Newtonsoft.Json, more potent but it's a package to install
File interaction can be done with the stuff in System.IO
I think the JsonUtility is enough, I will probably create a "save" class" and add data to it when I save the game.
Hey everyone,
I am working on a VR environment, I used Google Cardboard XR Plugin for Unity, it is going really well but I am having one issue where the cardboard Reticle pointer is not staying in the middle, it is dynamically moving left/right/up/down when I tilt my head, this is causing misalignment with the logic itself and recognizes objects incorrectly. Attaching photos for more context.
If anyone has any experience on how to solve this would really appriciate it...
Hi, I've been trying to figure this out for literally 24 hours. I'm completely new to Unity and coding and is desperate. Please help me...
I've been trying to follow this tutorial: https://www.youtube.com/watch?v=0T5ei9jN63M
🤖 Play Web Version: https://unitycodemonkey.com/unityPlayer.php?v=0T5ei9jN63M
✅ Get the Project files and Utilities at https://unitycodemonkey.com/video.php?v=0T5ei9jN63M
In this video we're going to make a Health System and a visual Health Bar.
It's going to be a clean and independent class that we can apply to anything like the player, enemies...
These are my scripts
I made sure patience bar is arranged accordingly in hierarchy
But my health bar just isn't moving, does anyone know why?
According to my debug, the bar is supposedly moving, and the patience percentage is calculating accordingly - but the bar itself just isn't moving
You already asked this in another channel, please don't cross-post
Oh sry 😓
@short hazel Do you mind reviewing my question, just to make sure it's suitable for this channel or should I use another one
i need help; i can't figure out where the problem is :')
VR usually goes in #🥽┃virtual-reality. But the crosshair not keeping itself centered seems like a calibration issue more than anything else
Depends if you have code that moves it or not
Thank you! I am using Google's scene but as you mentioned I just modified the script and made the dot in center at all time, just removed the dynamic piece altogether 😄
I think I fount the most helpful yt playlist for people to learn how to code(maybe)
Hey sorry guys, im new to unity and Im getting these errors, its an older version of unity. i didnt wanna risk updating the project to a newer one and breaking it so i kept it in its original version, i think these have to do with Dotween?? but theres 162 of them 🥺
Yep whatever version of dotween you're using isn't compatible with that unity version
I recommend updating both to the newest version
double click on one of them to bring up the code, then post that here
upgrade or downgrade? since the version of unity is 2k19
Upgrade
You are using version control yes?
Aka Git or PlasticSCM?
If so there's no risk in upgrading since you can revert at any time
If you're not using version control you need to start
ahhh okayy, ill see if upgrading works
Hi
Im trying to Flip my Gameobject who is a Child of my Parent "Player" but my code doesn't work with it
void Flip(float _velocity)
{
if (_velocity > 0.3f)
{
GameObject.flipX = false;
}
else if (_velocity < -0.1f)
{
GameObject.flipX = true;
}
}
In what wat doesn't it work?
Do you have a compile error?
A runtime error?
Is the code actually running?
Yeah i was writing it sorry ^^
What is GameObject here? Seems like it's the class name of GameObject but your code implies it's a SpriteRenderer, which is super confusing.
for now, im trying to use the code i used, for flip my spriterenderer, i don't realy know how should i flip my GameObject with the "Player"
Can you answer these questions please? Cannot really help you without it
yep
not sure what the picture is supposed to be showing.
When i flip my player, the mele range (circle on screen) doesn't flip, i tried to use "GameObject" because i was doing some test to flip it, i have error with FlipX because it doesn't work with "GameObject.flipX = false;", so im looking to know with what im supposed to change the "GameObject" to make the circle stay on right arm
I don't see where you got the idea that GameObject was appropriate here at all
so your issue is you are using the flipX property on your sprite renderer
all that does is draw the sprite in reverse
it doesn't actually rotate your object
so anything else on it will not rotate, including child objects, etc.
I recommend rotating the actual object instead of using SpriteRenderer.flipX
Rotating a GameObject is done via its Transform component
e.g.
// flipped
transform.eulerAngles = new Vector3(0, 180, 0);
// normal
transform.eulerAngles = new Vector3(0, 0, 0);```
Your velocity might never be negative as well, if it's a result of calculating a vector's magnitude
its Negativ when i go back in 2d plateformer
Can someone explain pls why my renderer bounds are behaving so strangely? I will be looking forward to your help.
using UnityEngine;
public class DrawRendererBounds : MonoBehaviour
{
// Draws a wireframe box around the selected object,
// indicating world space bounding volume.
public void OnDrawGizmosSelected()
{
var r = GetComponent<Renderer>();
if (r == null)
return;
var bounds = r.bounds;
Gizmos.matrix = Matrix4x4.identity;
Gizmos.color = Color.blue;
Gizmos.DrawWireCube(bounds.center, bounds.extents * 2);
}
}
Renderer renderer = gameObject.GetComponentInChildren<Renderer>();
if (renderer == null)
{
Debug.LogWarning("Renderer component not found.");
}
Bounds bounds = renderer.bounds;
float rayLength = bounds.size.y;
Vector3[] topCorners = new Vector3[4];
topCorners[0] = new Vector3(bounds.min.x, bounds.max.y, bounds.min.z);
topCorners[1] = new Vector3(bounds.max.x, bounds.max.y, bounds.min.z);
topCorners[2] = new Vector3(bounds.min.x, bounds.max.y, bounds.max.z);
topCorners[3] = new Vector3(bounds.max.x, bounds.max.y, bounds.max.z);
Vector3 topLeftCorner = topCorners[0];
Vector3 topRightCorner = topCorners[1];
Vector3 bottomLeftCorner = topCorners[2];
Vector3 bottomRightCorner = topCorners[3];
please share videos as mp4 since they can be embedded in discord. mkv cannot
Wondering why the numbers you're comparing are not identical then, it should be -0.3f and 0.3f to be consistent
oh. kk. 1 sec)
When you say strtangely what do you mean exactly?
Looks perfectly fine in this image
Are you aware that bounds are expected to be this way? Bounds are "AABB"s aka "Axis Aligned Bounding Boxes". Note the "Axis aligned" part - illustrated perfectly by the image.
But why are they separate from the object? Or do render bounds work differently than colliders?
they aren't separete from the opbject
they are bounding the object perfectly
No. because if you put:
else if (_velocity < -0.3f)
{
GameObject.flipX = true;
}
to be consistent the player will start the game by looking on the back.
Only if the game starts by immediately kicking the player backwards
Are they kind of drawing a square that can be described around that object?
If the player does not move, the velocity will be at 0, and neither if statements will pass
an axis aligned box that bounds the object. The smallest such box
oh... i see...
ty very much, i will kill myself rn because of this xD
In my project, the object did not change its rotation, and now that I have added it, the render bounds have shifted)
Is there any other type of bounds? Like collider bounds?
using Unity.VisualScripting;
using UnityEngine;
public class GroundChecker : MonoBehaviour
{
public LayerMask groundLayer;
public LayerMask baseLayer;
private bool isGroundedResult = false;
public bool IsGrounded(GameObject gameObject)
{
Renderer renderer = gameObject.GetComponentInChildren<Renderer>();
if (renderer == null)
{
Debug.LogWarning("Renderer component not found.");
}
Bounds bounds = renderer.bounds;
float rayLength = bounds.size.y;
Vector3[] topCorners = new Vector3[4];
topCorners[0] = new Vector3(bounds.min.x, bounds.max.y, bounds.min.z);
topCorners[1] = new Vector3(bounds.max.x, bounds.max.y, bounds.min.z);
topCorners[2] = new Vector3(bounds.min.x, bounds.max.y, bounds.max.z);
topCorners[3] = new Vector3(bounds.max.x, bounds.max.y, bounds.max.z);
Vector3 topLeftCorner = topCorners[0];
Vector3 topRightCorner = topCorners[1];
Vector3 bottomLeftCorner = topCorners[2];
Vector3 bottomRightCorner = topCorners[3];
bool topLeftHit = Physics.Raycast(topLeftCorner, Vector3.down, rayLength, groundLayer);
bool topRightHit = Physics.Raycast(topRightCorner, Vector3.down, rayLength, groundLayer);
bool bottomLeftHit = Physics.Raycast(bottomLeftCorner, Vector3.down, rayLength, groundLayer);
bool bottomRightHit = Physics.Raycast(bottomRightCorner, Vector3.down, rayLength, groundLayer);
isGroundedResult = topLeftHit && topRightHit && bottomLeftHit && bottomRightHit;
return isGroundedResult;
}
like this
I get the top corner points of the object and shoot a ray down from them
bounds is overkill for this
I've already figured it out)
But what method can be used to solve this situation?
like idk, mb another bounds?
oh i thought you figured it out
a few options
- Use empty child GameObjects at the positions you want
- get the corners you want with like
Vector3 topRight = transform.TransformPoint(new Vector3(0.5f, 0.5f, 0.5f));
Vector3 topLeft = transform.TransformPoint(new Vector3(-0.5f, 0.5f, 0.5f));
Vector3 bottomRight = transform.TransformPoint(new Vector3(0.5f, 0.5f, -0.5f));
Vector3 bottomLeft = transform.TransformPoint(new Vector3(-0.5f, 0.5f, -0.5f));```
But later this can become a problem, for example, due to the change in the size of the object. I used bounds precisely because the script will not be bound to variables, but will directly depend on the parameters of the object. (as I thought at the time)
wdym by change in size of the object?
If you are changing the size via localScale, then the transform.TransformPoint approach will already take that into account
hm
For example, in the Inspector I changed the height of the object. Now my ray does not reach the ground, because it hit a certain length, tied to a variable. This means that you will also have to change the value of the variable
in the Inspector I changed the height of the object
There is no "height" option in the inspector
do you mean y scale?
If you care about that then just multiply your ray distance by localScale.y
Why are you sending the rays from the top of the object though?
Why not from near the bottom?
Then the height of the object won't matter
In order to suddenly have my object a little underground.
it's the foundation. in my game
I kind of need to do 4 checks in the corners, and if they all pass it, then the object can be exposed)
Hey guys, I have a problem with my third person movement. It won't really allow me to use W-A-S-D the way it should be and faces not the best directions 😄
using System.Collections.Generic;
using UnityEngine;
public class ThirdPersonMove : MonoBehaviour
{
public Transform cam;
CharacterController controller;
Vector2 movement;
float turnSmoothTime = .1f;
float turnSmoothVelocity;
public float moveSpeed;
// Start is called before the first frame update
void Start()
{
controller = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
movement = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
Vector3 direction = new Vector3(movement.x, 0, movement.y).normalized;
if (direction.magnitude >= 0.1f)
{
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg * cam.eulerAngles.y;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
transform.rotation = Quaternion.Euler(0f, angle, 0f);
Vector3 moveDirection = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
controller.Move(moveDirection.normalized * moveSpeed * Time.deltaTime);
}
}
}```
any idea what the problem is?
I use the cinemachine for the camera:
Maybe further explain the actual results compared to wanted results. Log some data like the angle produced versus wanted.
Well, A key does the same as W and D the same as S
Ok im starting to Lose my Mind... can anyone explain that to me:
First Screen is My Project where he cant find the Callback to Override, Second Screen is the Documentation where it should CLEARLY exist...
I just want to have W - forward, A - left, - D - right, S - downwards
The code looks needlessly complicated for that
mine?
yes
What is the translation of that error in english?
It looks like it's meant for 2d movement
Any other tutorial doesn't really help
@wintry quarrybasicly just he cant find that Methode to Override
Shall I make a little video?
Which network framework is the video using and which are you using?
Netcode for Gameobjects (both)
It looks like there is just no method called OnStartClient
make sure you're using the same version of the package as the tutorial
up to date and in the Project
Okay, thanks for the help, I'll try to come up with something else for this)
@keen dew @ivory bobcat
im using that for my game aswell :D. that and Relay for client and server communication
Editor Version is Sync with Docu, and Netcode version...
https://docs.unity3d.com/Manual/class-NetworkBehaviour.html cant find the Version
Yeah this is UNET
@swift sedge can your sourcecode find those Callbacks?
Omfg...
you are using a unet tutorial
or documentation
Netcode for gameobjects documentation is here https://docs-multiplayer.unity3d.com/netcode/current/about/
Overview of Unity's Netcode for GameObjects for your multiplayer networking needs.
I tried so many scripts for third person movement but none really does the job I wanna have. Even the one from Brackeys 😄
what do you need?
does anyone know a way to randomly spawn objects withtin a plane? this one i'm trying isn't good (i tried spawning 1000 objects)
thanks alot, gonna dig into that
Basically third person movement 😄
Do you want something other than the standard strafing left and right movement? You shouldn't need to do any rotating for that (because rotating isn't involved)
you need relay and lobby aswell to have proper multiplayer
Nope 😄
@keen dew just that
void Update()
{
movement = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
Vector3 direction = new Vector3(movement.x, 0, movement.y).normalized;
controller.Move(direction * moveSpeed * Time.deltaTime);
}
have you used Input.GetAxisRaw?
yeah:
{
movement = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
Vector3 direction = new Vector3(movement.x, 0, movement.y).normalized;
if (direction.magnitude >= 0.1f)
{
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg * cam.eulerAngles.y;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
Vector3 moveDirection = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
controller.Move(moveDirection.normalized * moveSpeed * Time.deltaTime);
}
}```
var forward = transform.forward;
forward.y = 0;
var right = transform.right;
right.y = 0;
var direction = forward * input.y + right * input.x;
controller.Move(direction.normalized * speed * Time.deltaTime);```etc
Assuming top down
my player doesn't rotate now obviously
yeah like diagonal
You probably do not want to rotate and move with the same input..
Pick one behavior or the other for selected keys
Again, the standard WASD movement is that the keyboard moves the player but doesn't rotate. Mouse rotates the player but doesn't move. And you said that's what you want.
@keen dew @ivory bobcat that makes sense 😄 so i gotta have some code for the mouse that rotates the camera
If it's like WoW, you'd rotate with A and D and strafe with Q and E
yeah
so I want to move with WASD in the right directions (currently not the case lol) and rotate camera with the mouse in all directions
did you get this resolved ?
Assuming direction is relative to character and not the world else use Nitku's implementation #💻┃code-beginner message
mine is not tested, probably better to use something else
Mines isn't either 
hahaha 😄
Mobile discord coding without intellisense or looking up any API but the two logically should work for their specific use cases
using System.Collections.Generic;
using UnityEngine;
public class ThirdPersonMove : MonoBehaviour
{
public float speedH = 2.0f;
public float speedV = 2.0f;
private float yaw = 0.0f;
private float pitch = 0.0f;
public Transform cam;
CharacterController controller;
Vector2 movement;
public float moveSpeed;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
controller = GetComponent<CharacterController>();
}
void Update()
{
movement = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
Vector3 direction = new Vector3(movement.x, 0, movement.y).normalized;
controller.Move(direction * moveSpeed * Time.deltaTime);
yaw += speedH * Input.GetAxis("Mouse X");
pitch -= speedV * Input.GetAxis("Mouse Y");
transform.eulerAngles = new Vector3(pitch, yaw, 0.0f);
}
}```
@ivory bobcat @ivory bobcat that's how it looks like
w-a-s-d still doesn't feel right lol
Follow a tutorial
oooh i am 😄
before i had this but that seemed very complicated and unnecessary
Define "feel right". I also suggest using a tutorial if you haven't implemented basic characters movement functionalities before.
WASD faces different directions
i don't know if something in the settings is wrong or in the code
There shouldn't be any "facing" or rotating with the code suggested by nitku
okay
sooo update, updating didnt change anything but after fiddling i got it down to 60 errors 🥲 I added this script relating to the first error if anyone has any ideas. i can't find anything online
Alright, I report my results 😄
TBH it seems like mybe you have multiple copies of certain plugins in your project?
my plugins folder had two folders the left one being the cause of my pain atm but it came with the game template, the right one being dotween
would you repost the script including line numbers
sure sorry
you've definitely got duplicate scripts there
hmmm, okay thanks, ill have to have a deep dive tomorrow, but for now ima get to bed aha, thats enough for one day. ill post an update, hope youre right
thanks a lot for the help!
i caused an infinite loop, how do i get out of this?
press the "Immediate mode" button in the debugger
and do colliders = null
this will throw an exception
breaking you out of the loop
that didn't work too
you have to do it on line 57
the problem is the function which has while() is also called a lot of times
put the breakpoint on line 57
where is it called from
show
here
this shows me even less
number = 0
in the immediate window
and/or SpinningBoxScript.Type = null
isn't number out of scope?
since while() is the one causing the loop
get into the scope where it's in scope
with another breakpoint
break out of the while as suggested before, get into the scope where number is in scope and set number to 0
thanks
nvm it didn't work
i kept trying the moving the yellow breakpoint arrow and it somehow worked, thanks
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
oh shit sorry
did you fix it ? still waiting on code lol
private bool IsCloseToAnotherBox(float x_dim, float z_dim)
{ var boxPosition = new Vector3(x_dim, 1, z_dim);
var colliders = Physics.OverlapSphere(boxPosition,0.5f);
foreach(var collider in colliders)
{
if(collider.gameObject.tag =="SpinningBox" || collider.gameObject.tag=="Player" || collider.gameObject.tag == "Wall")
{
return true;
}
}
return false;
}
is this the correct way to avoid objects overlapping? it works but i still get occational overlapping
like here
the box's scales are all 0.25, and the overlapping sphere is 0.5
so there should not be any overlapping right?
start using Gizmos and view whats going on
i'm not sure how to paste this in another site
paste and hit save, send link
it's a bunch of little code blocks that culminate in a large one
i guess i'll just copy all those in?
send the whole script thats throwing the error
only the line number is relevant
but need context for the whole script
what do i change?
no not this ,
i mean this
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnDrawGizmos.html
you would see where exactly your overlap is and whatnot
i'm not sure where to use this, do i put
Gizmos.color = Color.yellow;
Gizmos.DrawSphere(transform.position, 1);
right under overlap sphere?
getting this error:
Dialogue.QueueSpeech (System.String text, UnityEngine.Vector3 position) (at Assets/Scripts/Dialogue.cs:90)
Dialogue.Start () (at Assets/Scripts/Dialogue.cs:53)```
on this: https://hastebin.com/share/nisaxewuve.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
did you read the description of the link? it goes in its own special method
queuedStrings is probably null
would this show me how the spheres would look like?
yep, it's not initialized
its static so unity doesn't new() and serialize it in the inspector, also because it doesn't serialize Queue type
welp, 30 minutes wasted on that. thank you!
well it was very obvious. the error gives you the line number of the code and the only thing on that line that could be null and cause an exception is queuedStrings. QED
guys, why it pops the red thing under the text, it won't work:
because u havent closed a statement
read what the underlines tell you
they're there for a reason
i dont think he's seeing the red line two lines above the obvious ones
What does the error say when you hover?
even it the if (inputManager.OnFoot.Interact.triggered)?
no thats probabyl Interact missing
read what error says
Code gets scanned top-to-bottom, always start with the topmost error
Severity Code Description Project File Row Deletion status
Error CS1061 'object' does not contain a definition of 'Interact' and no accessible 'Interact' extension method was found that takes a first argument of type 'object'. You're probably missing a using directive or assembly reference. Assembly-CSharp D:\Games\My project\Assets\Scripts\Player\PlayerInteract.cs 36 Active
Okay, good. Is this the first red squiggly error or the one from the second line?

One error often causes future lines to error
they are the only errors in this script, everything else is good
There is a small red error at the end of one line. Again, look from top to bottom . . .
Intractable is probably not a static class
This pic is updated from the original. You've fixed the first error now . . .
this is all the code
Good, one down. Now what's the next one
Now what does the next (topmost) error say?
Severity Code Description Project File Row Deletion status
Error CS0120 An object reference is required for property, method, or non-static field 'Interactable.promptMessage' Assembly-CSharp D:\Games\My project\Assets\Scripts\Player\PlayerInteract.cs 35 Active
this is line 35:
playerUI.UpdateText(Interactable.promptMessage);
You need an instance of Interactable to access the promptMessage field . . .
how do i do that, like private etc..?
You're trying to access it from the class itself but the field is not static . . .
@trail creek btw nice Gabibbo picture profile 
ty haha
r u italian?
yea
You're mixing up Interactable (the type), and interactable (the variable created one line above)
C# is case-sensitive
ohhh
ohhhh ok
one error down
there is the second one:
Severity Code Description Project File Row Deletion status
Error CS1061 'object' does not contain a definition of 'Interact' and no accessible 'Interact' extension method was found that takes a first argument of type 'object'. You're probably missing a using directive or assembly reference. Assembly-CSharp D:\Games\My project\Assets\Scripts\Player\PlayerInteract.cs 36 Active
line 36:
if (inputManager.OnFoot.Interact.triggered)
InputManager.OnFoot is an object it seems 🤔
I need some help. Iam making a tower defense game in 3d and i have 2 towers with an example height of 1.5 and 3. I have some cubes with a given layer to place the towers at. Now i want the towers no matter of their height to be placed on top of the cube with its button exactly on top. So basicly the 1.5 high tower being .75 above the cube and the 3 high one 1.5 above. I hope my problem is understandable heres my code iam changing the system rn so some parts are confusing. https://paste.ofcode.org/3azFEDEqDX5zHY6FUT2d6vn
yeah not entirely sure how Input System works, I assume OnFoot supposed to be the Input Action Map/
Yeah but it's probably that tutorial where they define their own InputManager, not to be mixed up with the one the Input System already provides
The error resides in the InputManager class.
Ahh had no idea there was such thing
if you want i can send the InputManager.cs?
yeah its naming issue
"OnFoot" is the trigger, it's the only tutorial that uses it, and apparently the only tutorial that makes a lot of people struggle lol
the new Brackys replacement for deltaTime on the mouse xD
except this one gives missing definition
this is the InputManager if it's needed:
You have to name it something else
hi
oh wtf internal readonly object OnFoot;
can i see the tutorial you followed for this
oh yea
The second video in the Lets Make a First Person Game series!
🖐In this video we are going to setup the foundations for our interaction system.
Come Join us on the Discord!
🎮 https://discord.gg/xgKpxhEyzZ
💚 Thanks for watching!
Helpful Links
https://dotnettutorials.net/lesson/template-method-design-pattern/
Yep line 12 is not supposed to be there
Ah I see what happened
They got the error, and used the IDE quick action "Create field in InputManager.cs" as it's what pops up first when you refer to an undefined member
Created it with type object since it can't know what type you'd like, and internal as it's the most restrictive, while still be able to access it from the outside
what does this new provide contacts option do ?
oh yeah internal dead giveaway generated from IDE , good catch
i deleted line 12, and now:
So you need to use the one on line 8. Make it public and change its name so it's OnFoot
ok ty
It's basically for https://docs.unity3d.com/ScriptReference/Physics.ContactEvent.html
okay, thank you
@short hazel i found this in the comments of the video:
Hey Everyone! I have only just realised there is some footage missing from the video!!!
You may encounter the error "'InputManager.onFoot' is inaccessible due to its protection level".
if you have this error you just need to change 1 line in the InputManager script.
Change this -> private PlayerInput.OnFootActions onFoot;
To this -> public PlayerInput.OnFootActions onFoot;
this is what you told me
ty
sorry for the ping

Yeah another trash tutorial lmao
At least it doesn't multiply mouse input with DeltaTime
How do you skip (not put in) video from a tutorial?
The Brackeys Effect™️
i literaly delete any video someone find coding flaws in
im too self conscious
btw it's working now
Yeah
awesome!
what was issue?
Turns out I was trying to reference an array in one script's awake() that only gets initialized/populated in another scripts awake()
So I had to move that code to start() instead
ahh yes good ol script execution order
Hello, Im following a tutorial on youtube to create a simple 3D game, when I press the action key "E", nothing happens, Im attaching a clip and the script in this thread. Could anyone please take a look and help a rookie out, thank you!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class doorCellOpen : MonoBehaviour
{
public float theDistance;
public GameObject actionDisplay;
public GameObject actionText;
public GameObject theDoor;
public AudioSource creakSound;
private void Update()
{
theDistance = PlayerCasting.distanceFromTarget; //referring to playercasting script variable
}
private void OnMouseOver()
{
if (theDistance <= 3)
{
actionDisplay.SetActive(true);
actionText.SetActive(true);
}
//enabling the UI text
if (Input.GetButtonDown("Action") && theDistance<=3)
{//button pressed, distance reduced = do the following
this.GetComponent<BoxCollider>().enabled = false;//disable collision
actionDisplay.SetActive(false);
actionText.SetActive(false) ;
theDoor.GetComponent<Animation>().Play("doorHingeAnim");//play anim
creakSound.Play();//play audio
}
}
void OnMouseExit()
{
actionDisplay.SetActive(false);
actionText.SetActive(false);
}
}
Log the distance and make sure the correct objects are referenced.
Thanks for responding, I have put every child (anim object, collisions, audio) under Door parent object and I referenced Door and every child one by one but the door just wont open, neither does the sound play. idk what Im doing wrong here
Place a log in the if statement for action down and see if it prints
