#💻┃code-beginner
1 messages · Page 560 of 1
the Transform lookAt is still the player
and check if u conected the script to the main camera
lemme get this on vid for ya
@steep obsidian !collab don't spam learning channels.
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
@helo guy
!kick 1323159891178819725 spam
babalolamahmud was kicked.
@lucid quiver
dude this script goes on the main camera not the man mesh
oh
also since ur camera is a child of ur manmesh parent u dont need to update camera position tho this is not suggested while using rigidbody lets at least get this working first
remove this line transform.position = lookAt.position + rotation * Direction;
and attach the script to camera
so player movement on manmesh and camera move on main camera?
and remove camera movement from man mesh
u can get rid of this whole paragraph
Vector3 Direction = new Vector3(0, 0, -distance);
Quaternion rotation = Quaternion.Euler(currentY, currentX, 0);
transform.position = lookAt.position + rotation * Direction;
u can remove
public Transform lookAt;
public Transform Player;```
Reading the action cessation.
so it should look like this now?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraMove : MonoBehaviour
{
private const float YMin = -50.0f;
private const float YMax = 50.0f;
public float distance = 10.0f;
private float currentX = 0.0f;
private float currentY = 0.0f;
public float sensivity = 4.0f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void LateUpdate()
{
currentX += Input.GetAxis("Mouse X") * sensivity * Time.deltaTime;
currentY += Input.GetAxis("Mouse Y") * sensivity * Time.deltaTime;
currentY = Mathf.Clamp(currentY, YMin, YMax);
transform.LookAt(new Vector3(-currentY, currentX, 0));
}
}
remove time.deltatime from both
ok do I need to keep the * and ;?
currentX += Input.GetAxis("Mouse X") * sensivity;
currentY += Input.GetAxis("Mouse Y") * sensivity;
and learn c#
I plan on it
I orignially tried to learn ue5 😭 quickly switched to unity 😂
unity's a better playground
C and C++ are not for the feint of heart! I never got the hang of pointers, that was a gauntlet of a class.
memory scares me about those languages
much easier to hop into and just try learn
from what ive heard its more hands-on management
I was using blueprints, it drove me insane
tbh java a c# are like pretty similar so it was easy for me to learn it
I took a Java class for my intro. Aced it. C++ kicked my ass.
does it work now or what?
well stay clear of the animator/vfx/shadergraph
I'm just hoping that when I eventually get the hang of this I can get graphics similar to ue5 especially fire and explosions
u can..
It does have syntax differences that drive me nuts. I started with Java, then Javascript, and now going to CSharp has been jarring.
Unity's HDRP pipeline is pretty good graphically
Why does it look like a pair of lungs?
i use URP and i can get really decent looking graphics..
its not 1:1 like unreal's
but its passable
yes almost, the directions are buggered tho, right = up left = down, down = left and up = right
ya especially unity has some custom stuff that defies all programming logic
And the documentation for CSharp and Unity are written to discourage newbs from learning, which is annoying.
vfx and shadergraph can allow u to make some really good fire/smoke/explosion effects
ooooh
pair that w/ some lights and tada
Least fucked up VRChat asset
oh right i might have dont the rotation quaternian thing damn
i keep forgetting this is look at fucntion
I will say I do like 1 thing in ue5 over unity, camera, movement and basic animations are already implimented
LookAt takes a position.
transform.LookAt(new Vector3(currentX, currentY, 0));```
lots of guys will say thats probably their least favorite part
using LookAt seems weird
the reason i stopped using UE.. is b/c it feels Tailored..
u need to make things how they expect u to make things
tailored?
ya it is here as well u just gotta know how to spawn a cinemachine camera
It has a lot of assumptions about how your game should work
ah
It feels very strange coming from Unity
ikr i have never used that
never used look at
if i were you Gorth.. i'd spend a day or so just reading/watching tutorials about camera systems and cinemachine
its a very important topic
@errant rock
What kind of camera movement are you trying to create here?
here change the last line to this
if u follow the lead of someone (in a tutorial for example) even if its not what u want.. at teh end..
u'll learn some things that are invaluable
I probs will learn cinemachine in the next itteration, atm I'm just tryna get the most basic things out the way so I can focus on making the game itself, once i've done most of the world, ai, cars.ect.ect I'll refine movement and camera.ect
for u to try to do a custom one
I can't think of a way for LookAt to make sense with mouse input like that
just following mouse pointer i was tempted to just give him my script
OTS / GTA style
mouse delta -> rotation
LookAt will cause the transform to rotate to point at a specific position in the world
that doesn't make any sense; as you move around, your camera will rotate
tbh i have nerver used it in my life
It sounds like you want mouse X movement to yaw the camera (left-right) and mouse Y movement to pitch the camera (up-down)
Is that correct?
exactly, yes rn I'm just copy and pasting things but it will teach me, knowing all the different values and how c# works compared to lua, I'm very autistic so I learn in weird ways 🤣
good.. every Quaternion.Method() is better imo
just try to follow one from start to finish..
dont selectively pick and chose what to paste together
thats gonna make for a bad time
until u learn more
If this is so, you can easily do this with Quaternion.AngleAxis
This method produces a rotation by a certain angle around an axis.
even if i use regular camer i just do transform.localRotation= something
see.. Quaternion method FTW!
private void RotateCamera()
{
// get our input
Vector2 inputValues = new Vector2(Input.GetAxisRaw("Mouse X"),Input.GetAxisRaw("Mouse Y"));
inputValues = Vector2.Scale(inputValues,new Vector2(lookSensitivity * smoothing,lookSensitivity * smoothing));
smoothedVelocity.x = Mathf.Lerp(smoothedVelocity.x,inputValues.x,1f / smoothing);
smoothedVelocity.y = Mathf.Lerp(smoothedVelocity.y,inputValues.y,1f / smoothing);
currentLookingPos += smoothedVelocity;
// rotate the camera on it's X axis (up and down)
transform.localRotation = Quaternion.AngleAxis(-currentLookingPos.y,Vector3.right);
// rotate the player on it's Y axis (left and right)
controller.transform.localRotation = Quaternion.AngleAxis(currentLookingPos.x,controller.transform.up);
}``` i like `AngleAxis` too
lookInput *= Time.unscaledDeltaTime;
yaw += lookInput.x;
pitch -= lookInput.y;
yaw = Mathf.Repeat(yaw, 360);
pitch = Mathf.Clamp(pitch, -87f, 87f);
Quaternion turnRot = Quaternion.AngleAxis(yaw, Vector3.up);
Quaternion lookRot = turnRot * Quaternion.AngleAxis(pitch, Vector3.right);
Here is a snippet from my humanoid brain.
Before anyone points it out: I divide mouse input by unscaledDeltaTime in an input processor. That line is correct.
@lucid quiver tysm this is loads better!
glad it works
even if u dont implement cinemachine right now u should look into vecotor lerp to decrease the camera stutter
I calculate the turning rotation separate from the full look rotation so that I can use the former to control the body and the latter to control the head.
also having the camera as a child to a rigidbody is not ideal
any idea why objects are showing behind my canvas dexpite the z level
real quick... my brain cant comprehend atm..
this is for my god cam... zooms in and out and pans..
question: does this line make it pan slower when zoomed in.. or faster when zoomed in?
well what kind of element is it?
UI, Sprite, what?
anything, sprites, uis
its part of the canvas
if u dont want that to be the case.. u need to use a world-space canvas
or an overlay canvas
well, how do you interpret newZoom.y ?
That wouldn't happen in the scene view, mind you
and this looks like a screenshot from the scene view
(but yes, an overlay canvas draws on top of everything -- it isn't rendered along with the rest of the scene)
I will, sorry to be a pain there's 1 more thing i could do with in this script
yes?
have the character rotate side to side with the camera even when not moving, coz atm if I don't move the character the camera feels completly seperated
SpriteRenderer is not a canvas object. if you want that on the canvas it should be an Image component
oh i removed image before because i wanted a way to disable its visibility without deactivating the game object
you can disable the Image component too
well thats tricky since u have the player and camer under the same parent
sorry im dumb how does one go about this
make a thread this is gonna be long
ah
the exact same way you do for a SpriteRenderer
camera shite coz i'm dumb
1 sec.. im about to hop on unity.. so i may be able to figure it out real quick
if(Input.mouseScrollDelta.y != 0)
{
newZoom += Input.mouseScrollDelta.y * zoomAmount;
// Clamp the Y axis for vertical zooming (5 to 100)
newZoom.y = Mathf.Clamp(newZoom.y,5f,100f);
// Clamp the Z axis for depth zooming (-5 to -100)
newZoom.z = Mathf.Clamp(newZoom.z,-100f,-5f);
}```
ew.. hard coded values lol
i replaced all instances of spriterenderer with image but i get this now
Assets\Scripts\SkillConnectionComponent.cs(9,13): error CS0246: The type or namespace name 'Image' could not be found (are you missing a using directive or an assembly reference?)
are you missing a using directive
make sure your !IDE is configured so you can add the correct using directive with the quick actions
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
good news: it works
bad news: big
yes well your scale previously was pretty huge
i might want to tone that down
How do you set up the scren resolution i finished the game and when i gave i to my friennd who has a smaler monitor he couldnt see most of the things and also my game was a little odd stuff was smaller and wasnt where i placed them is there a tutorial or smth?
You had sprite renderers on your canvas originally, right?
In that case, the default PPU (pixels per unit) of 100 would mean that 100 pixels of sprite take up one unit of space.
On an overlay canvas, one unit corresponds to one on-screen pixel
So everything is going to be 100 times larger now!
perfect
uhm, guys? I am making a drag and drop into my inventory yet it does not work properly, for example the item that I want to drag at (1|1)... if I drag and drop it, instead the item at (2|6) moves like my mouse needs to be on a whole different position. I already have screen space - overlay, I checked the content position etc
We would have to see code...
You need to change the anchoring settings of your UI objects so they're positioned relative to the corners/edges of the screen instead of the center by default. The pinned messages in #📲┃ui-ux have links on how to do that
thanks
in particular, you'll want to read
https://docs.unity3d.com/Packages/com.unity.ugui@2.0/manual/UIBasicLayout.html
also if you're using an orthographic camera (which would be typical for 2d games that don't need depth perception), you will want to also look into how to calculate the desired orthographic size for the camera to ensure it is the correct size. and supporting different aspect ratios without showing extra content would need letter boxing
(notably, Cinemachine can do this for you (: )
thanks all now i need to learn all this stuff
using UnityEngine;
using UnityEngine.EventSystems;
public class DraggableItem : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler,IPointerDownHandler
{
[SerializeField] private Canvas canvas;
private RectTransform rect;
private void Awake()
{
rect = GetComponent<RectTransform>();
}
public void OnBeginDrag(PointerEventData eventData)
{
Debug.Log("hehe");
}
public void OnDrag(PointerEventData eventData)
{
Debug.Log("haha");
rect.anchoredPosition += eventData.delta /canvas.scaleFactor;
}
public void OnEndDrag(PointerEventData eventData)
{
Debug.Log("hoho");
}
public void OnPointerDown(PointerEventData eventData)
{
Debug.Log("Pointing");
}
}
but on other tutorials it works perfectly
but on mine it does not
can I do live?
but how though? yeah
and a Graphics Raycaster
yes
so you're saying that the item doesn't move as quickly as the mouse pointer does?
or moves faster, perhaps?
just checking.. those are the two normal culprits.. ppl forget to add them
both it registers graphic raycaster but on utterly different position, its not about movement, its about position, I have to use my mouse far next to my item instead of on it
hi y'all, a quick question: when I do transform.position for a cube, is it the position of the center of the cube?
or is it the position of one of the vertices ?
For the default Unity cube, yes.
It's whatever the origin of the mesh is
ok
set your tool handle to Pivot instead of Center and you'll see the point that would be considered its pivot point/transform.position point
As long as your tool handle position is set to "Pivot" you will see the position in the scene view when the object is selected.
nah it just mispositions it
like very much
Thanks, also I may not be very sharp (unlike C sharp), but if I want to define a target and the renderer, I cannot define it in the declaration? I have to define it every time step in the update process ?
for example I was putting this before the void start thing, but apparently it is not good
private double X2t;
private double Z2t;
private Target = GameObject.Find("Target");
private rend =Target.GetComponent<MeshRenderer>();
You can't use things like GameObject.Find in a field initializer
That winds up running at very interesting times
so if I keep the same object how should I do ?
should I declare it both in the start and update sections ?
You should assign a reference in the inspector, ahead of time
If this is a prefab that needs to reference an object in the scene, then see...
this is...very simple, really
much less prone to blowing up than using GameObject.Find
I got the anchoring part i set it up and i instaled cinemashine but i have no idea how to use it is there some document or smth cuz i cant find it .
how can I show live or vid to show my problem?
screen record and post
my camera movement is incredibly stuttery as is my movement, any ideas why? hopefully this is the right channel for this
i coded this all from scratch and i'm very bad at 3d so there's likely something stupid
will read this, tysm
hey guys, one of my packages i think is an old version, but says its up to date, and theres no option to update it
only mp4s embeds
since its nested..
im guessing its a scaling issue..
the actual button/collider is not where u think it is
how can i use nature/soft occlusion shaders if i am using a urp 3d template?
firstly dont attach camera directly rigidbody and also check out lerp to smooth out the camera position update
im looking right now.. i was thinkin there was a debug for UI to show u everything's colliders an whatnot cant remember where or how to find it
#🔀┃art-asset-workflow, better yet #archived-shaders
enable the gizmo's
it should show the green square around w/e element u have selected in the hiearchy
huh?
it doesnt show the bounds in my case
it should when its selected in the hiearchy
without being able to see the bounds.. ur just guessing its all correct
all images have one
also, make it a habit to check the game-view and the scene-view when ur debugging and figuring things out..
then it could be the scaling of the game-view..
ohh
if the UI's anchors and stuff get messed up.. if its scaled higher than ur scene-view for example
for example.. (this is another thing i do quite regularly when making UI)
stretch and squash the heck outta the game-view and inspect the scene-view at the same time.. to make sure everything moves and scales how it should
still not working but again tysmm
Hey, I'm looking to recreate a grappling hook like the one in the right video. I've got a prototype working (left), but now I want to make it collide and bend around obstacles. How would you recommend I go about it? Should I:
- Make the line out of a chain of joints
- Dynamically create joints based on where the line collides
- Something else?
The line can shrink when the player holds LMB, so I feel like 1) would be a little cumbersome. But with 2), I'm not sure if it could handle more complex shapes. Any tips?
Verlet (Integration) Rope Sim
Perhaps the latest version of that package is only available on a newer version of the Unity editor.
awesome, that's the keyword i was looking for, thanks!
reminds me of Worms2 Roping mechanic
can it generalize to 3d?
ya, it'll work for 2d and 3d
bless, thanks!
save ya some time huntin
theres some better ones out there tho..
omg lifesaver 🙏 tysm
this one looks smoother
but its 2d
verlet rope was a game-changer..
after trying to make realistic type ropes w/ hinge-joints and failing miserably
lmaoo i tried that a little bit and had the same result. i knew there had to be a better way
currently migrating to unity 6, hopefully this fixes it, thanks
You can check which version of unity you need in the package's documentation
mildly confusingly, it won't show you the version for the package version you've selected, but you can see it for the others...
If i set the aspect ratio to 16.9 and my friend has a difrent monitor than mine will he be able to play my game normaly will he see evertinhing normaly or will the object and the scene not be all visible?
was the information you received about that earlier not sufficient?
Assets\TextMesh Pro\Examples & Extras\Scripts\VertexZoom.cs(153,44): error CS0029: Cannot implicitly convert type 'UnityEngine.Vector4[]' to 'UnityEngine.Vector2[]'
I updated to unity 6, and this one script has like 12 of these errors, it's a engine script
what do i do with that xD, I have no idea what that script even does
It's an example, if you're not using it then delete it
thankyou!
YES you guys are great, I can finally use Rpc
+1 @north kiln +1 @swift crag
i did the anchors thanks for that but the cinemachine i just cant figure out i added it to the game and its normal but i dont know how to use it so that it adapts to the monitors ratio i cant find nothing on that everything is about tracking objects and stuff and its my first ever game without a tutorial i just want my friends to play it lol
you don't have to use cinemachine to do that. i gave you the keywords you can use to research how calculate the orthographic size manually
what key words
research how calculate the orthographic size manually
ok
you should learn how to use cinemachine though if you aren't using it. it will be better camera controls than you'd be able to make manually
there's documentation pinned in #🎥┃cinemachine to learn how it works
i will Fen told me that cinemashine cand do what u told me so i went with it im reasrching now about manull calclation
right but you have to actually be using cinemachine for your camera. you can't just slap cinemachine into the project and expect it to do that automatically
Cinemachine can move the camera so that a set of objects are all in-frame
i get that and that was the problem cuz i dnot know how to make i do that lol
ill learn more about it
using UnityEngine;
public class NetworkPlayer : NetworkBehaviour {
// Networked variable for health
[SerializeField]
private NetworkVariable<int> health = new NetworkVariable<int>(100); // Default health
private void Start(){
}
private void Update(){
}
[Rpc(SendTo.Server)]
public void reqMovePlayerRpc(){
GameObject playerCamera = gameObject.transform.GetChild(0).gameObject;;
Vector3 movement = Vector3.zero;
Vector3 camForward = playerCamera.transform.forward;
Vector3 camRight = playerCamera.transform.right;
if (IsClient){
}
movePlayerRpc(direction);
}
}
``` So I am trying to call a method on the GameManager object that takes care of serverside logic, but the client cant find the method, how do I make it so the client can find the method, should I search for the gamemanager object and then find it's script, and call the method like that?
you do not appear to have a movePlayerRpc method declared on this class. do you perhaps mean to call it on a reference to another object?
movePlayerRpc is declared on my GameManager object, I'm trying to invoke that method with parameters sent by a client, so that the server (GameManager) can reply with an updated position for the player
I'm just not sure what the best way to do this is
right, and because it is not on this object, you need to call it on that object. just calling movePlayerRpc(direction); is the same as doing this.movePlayerRpc(direction); but again, this does not have that method. so get a reference to the object that does. and maybe consider learning how c# works before attempting to do multiplayer
Lol I know how c# works buddy, unsure of how this multiplayer module works though, that's why im checking.
your issue has nothing to do with multiplayer and everything to do with calling a method on the wrong object
I was thinking that there must be another way, because giving the client a reference of the server object, and it's scripts sounds like a bad idea for security sake
and if it were solely a multiplayer issue, then #archived-networking is the place for that
I'm not even seeing where some of those variables are being declared
the only things that are not declared are movePlayerRpc and direction
rest of the code doesn't matter, the only part im trying t ofigure out is calling the method on the gamemanager object without giving the client a reference of it
the rest of the code is unfinished, i mmigrating single player code to multiplayer
Oh yeah im blind I see them ;p
my guy, these objects are all on the client too. just like literally anything else in c#, if you want to call a method on a specific object then get a reference to that object
alright thanks haha
var speed: float = 5; // units per second
var turnSpeed: float = 90; // degrees per second
var jumpSpeed: float = 8;
var gravity: float = 9.8;
private var vSpeed: float = 0; // current vertical velocity
function Update(){
transform.Rotate(0, Input.GetAxis("Horizontal") * turnSpeed * Time.deltaTime, 0);
var vel: Vector3 = transform.forward * Input.GetAxis("Vertical") * speed;
var controller = GetComponent(CharacterController);
if (controller.isGrounded){
vSpeed = 0; // grounded character has vSpeed = 0...
if (Input.GetKeyDown("space")){ // unless it jumps:
vSpeed = jumpSpeed;
}
}
// apply gravity acceleration to vertical speed:
vSpeed -= gravity * Time.deltaTime;
vel.y = vSpeed; // include vertical speed in vel
// convert vel to displacement and Move the character:
controller.Move(vel * Time.deltaTime);
}
If I add this to my character movement script would it correctly implement gravity so that my character doesn't float and can actually interact with the ground?
Why is the camera in another position far from where it should be?
what does this mean?
It means you wrote invalid code
you likely have messed up braces with code outside of the class
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
are you certain this component is attached to the camera and that you have the correct object referenced in the CameraPos variable?
^ the code
this isn't javascript, we don't declare methods with function, you need to use a return type
I mean you literally wrote JavaScript in here lol
and var is not a valid field type
You should learn the basics before trying to jump into a game
ffs I got it from a unity tutorial 🤦
you should use a tutorial from sometime in the last decade
that's legit what I'm doing?
One from 15 years ago?
legit
Close 😄
try sebastian lague's tutorial its a bit old but he explains things in a very begginer friendly way
now show it at runtime. and don't crop the screenshots so that half the useful information is hidden
for gravity?#
gravity is just downward force every frame
u can just use addforce no?
no because they appear to be using a CharacterController
of course there are hundreds of modern CC movement tutorials that include gravity, so i have no idea how they managed to get one from 2012
if ur a beginer maybe try learning a bit of the basics of c# first it will definitely help
google 🤷
try youtube next
click the CameraPosition object assigned in the variable there and see what it highlights
yes, but support for it was dropped a decade ago
https://assetstore.unity.com/packages/essentials/starter-assets-thirdperson-updates-in-new-charactercontroller-pa-196526
Unity has some templates you can rip apart. Most use the character controller component
character controller isnt very difficult once u get a hang of it but its not something i would start with if i didnt know the basics ... just try the old input system first
Raziel that camera script u helped w earlier, do u know why I can only look 180 degrees? I cant look behind my character to spin him around
oh you know what, your tool handle is set to Center rather than Pivot. so you aren't seeing that the object that has this component is in the correct spot. it's your camera that is offset from that
there was a Mathf.clamp that u implemented
probably thats the issue
this is what happens when u copy code without understanding it
remove the clamp if u want full rotation
I'm guessing cinemachine would fix all these issues?
well ya u wouldnt even need script for the basic functionality that u want
fuck it how do I install it
bet
ooo ok
playerCamera = gameObject.transform.GetChild(0).gameObject;;
movement = Vector3.zero;
camForward = playerCamera.transform.forward;
camRight = playerCamera.transform.right;
if (IsClient){
// Calculate movement based on input keys.
if (Input.GetKey(forwardKey)){
movement += camForward.normalized * moveSpeed;
}
if (Input.GetKey(leftKey)){
movement += -camRight.normalized * moveSpeed;
}
if (Input.GetKey(backwardKey)){
movement += -camForward.normalized * moveSpeed;
}
if (Input.GetKey(rightKey)){
movement += camRight.normalized * moveSpeed;
}
gameManagerScript.movePlayerRpc(movement, clientID);
}
}``` ``` [Rpc(SendTo.NotServer)]
public void movePlayerRpc(Vector3 movement, ulong clientID){
if (IsServer){
NetworkObject playerObject = NetworkManager.Singleton.ConnectedClients[clientID].PlayerObject;
Rigidbody rb = playerObject.GetComponent<Rigidbody>();
// Set the Rigidbody's velocity for snappy movement.
rb.linearVelocity = new Vector3(movement.x, rb.linearVelocity.y, movement.z);
}
}``` Im confused why this isn't working, Im sending movement data to server, server responds by moving the player, but im not sure why it has to send info out again afterwards
#archived-networking for networking related questions.
is there a trick to display the Scene class into the inspector? So you can LoadScene(sceneField)
it's atleast less prone to failure caused by renames/reorder in scenelist
there are assets that make it easier to do that, or you can write a property drawer for int or string that displays the scenes in the build list as a dropdown (which is what most of the assets like NaughtyAttributes does)
but the Scene itself is a SceneAsset which is a type from the UnityEditor namespace so naturally it won't be available in the build
oh, didnt know this part
makes it a little clearer why unity didnt display it by default yet
there is an issue with this layermask i cant seem to figure out if anyone wants to help
it doesn't look like a layermask issue, it looks like you are trying to check for a tag that does not exist
show it, because it apparently does not exist
tags != layers
so where is the Points tag?
#archived-networking and be sure to explain which networking framework you're using as well.
kk
Hey, quick question. I'm having some difficulty, and my code is calling a 'stack overflow'. Whenever I search it up it keeps coming out as it calling back to itself, whenever my code is going to different gameobject scripts (hopefully). Here's the code that its saying is having the stack overflow:
dealerCardValueonHand = Dealerhand.GetComponent<DealerCardValue>().handValue;
(Note, this is in a script called 'DealerDeckManager', and is on a DealerDeckManager object. DealerCardValue is on the DealerHand object.) If it helps, here is the DealerCardValue script:
[SerializeField] public int handValue = 0;
public TMP_Text dealerHandValueText;
public void Update()
{
dealerHandValueText.text = "DealerHandValue: " + handValue.ToString();
}``` Any ideas of how to fix this? I've never had this kind of error, so that's why I'm confused.
can you show the full stacktrace for that exception
stacktrace? Is that the error message? If so, here you go.
(whenever you do have a chance to respond, can you @ me? I have to do something, and may not be able to check if I have a response. Thanks!)
the error is not in the code you posted
It's not? Whenever I click on it it transports me to this
public void DealerDrawCard()
{
playerDealCardButton.SetActive(false);
playerStandButton.SetActive(false);
playerSpecialCardButton.SetActive(false);
dealerCardValueonHand = Dealerhand.GetComponent<DealerCardValue>().handValue;```
stack overflow happens typically when you call a function recursively, a common one is an event triggering itself (possibly indirectly)
Oh, I see it now. Thank y'all so much!
btw, for better performance that code should be this (saves you from creating two new strings and a mesh each frame)
{
dealerHandValueText.SetText("DealerHandValue: {0}", handValue);
}
Thank you so much! Didn't even realize SetText was a thing 😅
I am new to unity and trying to make a fishing game. I want each fish to have multiple values what is the best way to do this?
ScriptableObjects
I want each fish to have multiple values
What do you mean by this?
I want to have a sell value, Id, and name variable but I don't know the easiest way to do this
just make those fields on a script
public class Fish : MonoBehaviour {
public int SellValue;
public string ID;
public string Name;
}```
you can make prefabs with this script on them
and set the values as you wish for each one.
you could also use ScriptableObjects as Zyme mentioned, with similar fields
ok thanks
i used scriptable objects for items and enemies and dungeon generation variables etc in my project and i dont get the hype
dont think ill do it again
lol :F
public class Explosive : MonoBehaviour
{
private float health = 10f;
public GameObject explosiveObject;
public ParticleSystem explosionParticle;
public void TakeDamage(float amount)
{
health -= amount;
if (health <= 0f)
{
Explode();
}
}
void Explode()
{
Destroy(explosiveObject);
explosionParticle.Play();
}
}
any reason why this isnt working?
Define "isn't working"
i fixed it its okay
cause i was using the same function for other targets that werent explosives, so it wasnt disappearing since it uses a different script
im smart trust me 😅 (im not)
any reason why the particle isnt working?
{
explosionParticle.Play();
Destroy(explosiveObject);
}```
nvm i fixed it, just had to add this line of code
explosionParticle.transform.parent = null;
How can i access and copy/past structures made with tile maps within scripts? for example, if i had this structure(image 1) within this tilemap(image 2), within a script, would it be possible to clone this structure without creating a new tile map or doing it through .settile?
possible to clone this structure without creating a new tile map
Sure.
or doing it through .settile
I mean you would of course need to set tiles to clone it. Why do you have that restriction?
I got the error: MonoScript could not be found
and i figured out that it can only be used in Unity Editor but not in runtime application
I am using MonoScript like such
class Skill {
int atk;
virtual void when_turn_starts() {}
...
}
and make a script for different skills
and attach them to corresponding scriptableobjects
how can i have access to the scripts in runtime app?
You can either:
- Use polymorphism
- Use a simple enum and switch statement
- Use a dictionary and delegates
i more meant manually doing a settile loop (ie me visually looking at the structure and using settile to do it), sorry for the confusion
what should i look into for being able to clone the structure?
Just GetTile/SetTile
in a loop
alright, thank you!
last question, is it possible for me to divide areas/structures in a single tilemap into seperate objects (whilst still being in that tilemap)?
A tilemap is a single component on a single GameObject
so no, that doesn't really make sense.
alright, ty
lemme check them out later thanks!
It is very unclear what you want. If you want to open scripts, I suggest you follow one of the many tutorials of properly setting up Unity with Visual Studio as the !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
• :question: Other/None
i fixed it
how did he get different options in camera?
This is a coding channel. Ask these things in #💻┃unity-talk or look for the correct channel #🔎┃find-a-channel
People will help you with the code when able to
I'm not sure what you mean with "punishes that amount of buttons and weapons has to be the same but it already is"
i need help too 💀
!ask, also https://dontasktoask.com/
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
what does this mean and how do i fix
open the script
at the top you must have accidentally deleted the monobehavior part or if you are following a tutorial then you are misusing the script
hi i have a problem, im trying to do a multiplayer game but the two characters are confusing movements, even tho im moving lets say player one it moves the secpond one, it seems that only one player moves although im playing from the other one
also the camera glitches too
ok nvrm i fixed it
if you made the script a couple moments before you encountered that issue, this is typical behaviour with unity. you just need to give it a second to compile the script
it doesnt work even one hour after
now i deleted it and readded it but it still doesnt work
open the script
what?
exactly what I said, perhaps you should learn some c# basics before continuing
thats what im doing
What tutorial did you follow to create what you made here?
https://www.youtube.com/watch?v=VF9UUixCvUs&t=112s&ab_channel=ChargerGames i changed sky added plane and circle colored it and now im putting movement script
Build 6 Full Games With Unity 2023 : https://bit.ly/3GUOYYh
(12+ Hours of Video Content)
Best Game Development Courses:
-
Unity Android Game Development : Build 10 2D & 3D Games:
https://www.udemy.com/course/unityandroidgamecourse/?referralCode=DCB2B7945CF67B1BDB67 -
Unity By Example: 20+ Mini Projects (20+ Hours):
https://www.udemy.com/un...
Timestamp the part?
this is not 'learning C# basics'
my question is how do you see an error about a script and not even open the script to check
If there's a compiler error, Unity will show it in the console
8.00
Nowhere in that timestamp does it look like anything you did. Maybe follow it?
https://paste.mod.gg/fzvfwdvrnamx/0 why is my jumping/falling weird? I wanted to make the player fall faster and prevent too much horizontally movement but linearDampening seems hard to work with. Anyway to make the jump feel smoother and less floaty?
A tool for sharing your source code with the world!
what is this enum im dumb its a layer mask
yes i made script named PlayerController and drag it into sphere
at bottom
You made a script called PlayerController and you didn't modify it at all?
idk how to modify i just did what he did
not according to your code you didn't
you are pushing the player down each fixed update when they are falling so the player will get faster and faster, is this intentional? Remember there is a difference between the force modes used!
Can you not see the difference in your script and their script? Just visually? It's extremely different.
i cant see difference
wym
Baffling. This is theirs. You cannot compare with yours and see?
you did not make a script called PlayerController
I did that to see if working correctly but sometimes itll push me down instantly and other times i can slide around the air for a while before being pushed down
Add some debugging to your script so you can actually see what is happening rather than just guessing
i changed it after it didnt work because i incorrectly saw it in tutorial
Seriously?
That's still not what the tutorial says. Are you truly about to take the worst follower of a tutorial before the year is ended?
Literally just watch the tutorial and copy their text. It is beyond simple.
And delete all of the rubbish you have done already
is it better now
Alright good luck. Not wasting my time with this further.
no, you still have too many scripts
i literally didnt get to text
ok, so now change it to match the tutorial
wait
@echo kite
public class PlayerController {} is WRONG ❌
public class PlayerController : MonoBehaviour {} is CORRECT ✅
unity crashed
ty i think i fixed it
everyone was trying to get you to see this clear error with how the script was defined. A new script made in the editor project window will have this format already.
Hello, is there a way to read/check/uncheck an UI Toggle ? I tried do read the element like my Label:
```
Label name_1 = UIDocument.rootVisualElement.Q<Label>("BoostOneTitle");
name_1.text = "toto";
var check_1 = UIDocument.rootVisualElement.Q<Toggle>("BoostOneCheck");
Debug.Log(check_1.isOn);
```
But isOn not working (I think I'm not correctly "declaring" my Toggle). Someone can tell me why it's not working please ? ^^
you need to use .value
also #🧰┃ui-toolkit
Ty it's working! But wtf the documentation say to use isOn xD
It's more possible that I don't understand fully the documentation 😛
that is the UI docs not the UIToolkit ones
Aaah I found the other doc with ur keyword "UIToolkit" ! My bad ty very much I didnt knew that 😄
pro tip.
whenever you see VisualElement it's UIToolkit
noted, ty
Ty 😄
wheres input manager
brother
Read the error message
And please don't say that you don't know where to look, it's right there
Also, not a code question
y screenshot and not read
i have to think abt my issue for at least 5mins before considering to ask here
thinking for just 5 minutes is like scrolling 5 minutes on tiktok... you should consider checking documents or doing a google search before asking for help.. probably like 1 hour or more hen you dont find a solution...
most problems are solved with a little search, but too much people are so lazy asking the simplest questions.. as if people today have an attenion span of 5 minutes..
They do have an attention span of 5 minutes, which is quite wild
i probably ask for help after 3 days not fixing an issue or not finding whatr the problem is ^^
maybe even less
actually 5 minutes seems quite long for todays yoof
5 minutes today seem like a whole liefspan^^
then bump it down to like 30 seconds (5 minutes was a bit generous)
i think sometimes people dont understand problem solving is the best part on development.. it opens your eyes to solutions you never thaught of...
"Why read error when discord tell me answer"
why thinking when others can think for me^^ ..
good point, the 'you read the docs so I don't have to' attitude
I remember when I first was learning programming years ago. I read the java intro docs a lot and tried to do the official tutorials to learn. Now it's watch some random YouTube video and learn nothing...
I think bug hunting and problem solving is pretty enjoyable, And it furthers your knowledge. I blame TikTok for people not reading more than 5 words now 😔
It's gonna get worse with AI generating crap people don't understand
anything short related
really
Clearly there are limits to it being enjoyable, no one wants to spend 5 hours on one small problem
as i started i loved to surf on stack^^
my first real job, many many years ago. Day one pointed to 13 3inch binders for HP3000 programming and told, read them all
Oo sounds like fun haha. I'm glad now it's mostly digital but I have some books
They wanted you to understand what you were programming, so that was a necessity
I agree digital is easier and more readily accessible but, you can't beat turning a page
Yeah it really sucks that videos have become the norm. Personally I cannot learn like that reading is always the best way
And it's not a necessity for Game Dev today?
Also I would like to have a C#, Java, and C++ (actually I have a C++ book 😅 ) hard copy at my disposal as they are extremely nice
It is
yep, it's nice to be able to annotate books, can't do that with a YT vid or online docs
my first project ive done was directly a bot.. cause i hated the grinding part on Ragnarok Online ^^ it took a while till i got something to work but at the end it was my private bot.. never used by others.. so it was 99% undetected if i would get cuaght i knew it was my failure on coding...
especially the understanding part
I have a cpp book but I use cppreference mostly. Msdn is amazing for c# docs.
Well then I guess I know what website I'm going to when the inveitable day of learning C++ comes
and i loved it.. i probably coded more on the bot as playing the game at that time.. everytime i ve seen a problem i tryed to fix it as fast i could... and it was a nice entry with cheat engine and a bit reverse engeinieering.. memory scanning etc.
O'Reilly books are the best
i think i stil have somewhere c++ for dummys^^ never read it really..^^
the dummys books where somehow nice to..
Read the error message, it points directly to it
nvm
i couldnt find "edit" before
now i found it
what do i do here
you should see "Axes" which is a dropdown menu, drop it down then drop down Vertical and you should see the picture below (without Horizontal), you then would change "alt positive/negative and positive/negative buttons" to the respective value, you can probably just copy mine
Also this is an #🖱️┃input-system question
thats a default tho
Its probably case sensitive so put "Vertical" and not "vertical" and try again
Make sure you spell "Vertical" right in your code
ohh
hello guys when i click my script and its supossed to take me to my script in visual studio it show nothing how do i fix that
double click
ik but it didnt work
did it open VS?
screenshot for us what "nothing" is
so provide a screenshot of what it did do
btw, people who do cry and sob reaction emojis make themselves look like babies
do you have any IDE installed
#stop_IDE_go_nvim
lol, only if you don't want to receive any help on this server
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 5f;
public float jumpForce = 5f;
public float groundCheckDistance = 0.1f;
private Rigidbody rb;
private Transform groundCheck;
void Start()
{
rb = GetComponent<Rigidbody>();
groundCheck = transform.Find("GroundCheck");
}
void FixedUpdate()
{
// Get input
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
// Calculate movement direction
Vector3 movement = transform.forward * vertical + transform.right * horizontal;
// Apply movement
rb.linearVelocity = new Vector3(movement.x, rb.linearVelocity.y, movement.z) * moveSpeed;
// Jump
if (Input.GetKeyDown(KeyCode.Space) && IsGrounded())
{
rb.linearVelocity = new Vector3(rb.linearVelocity.x, jumpForce, rb.linearVelocity.z);
}
}
private bool IsGrounded()
{
return Physics.Raycast(transform.position, Vector3.down, groundCheckDistance);
}
}
Can someone help please I can't get jump to work
i was folliwng nattygamedev till i found he doesnt post anymore and quiot his tutorial so had to swtich to other channels to find how to implement guns and i think the looking around code from nattys is causing some issues with this new code and idk how to fix
code from input manager]
its not allowing me towalk around anymore and only makes me look
kinda took a picture but missed out of the actual line numbers ;p
sorry sorry
paste sites are better though if you do want quicker help
gotchu
is there a way for me to send u a link to the paste ofcode or i gotta ss
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
this is the original input code
and then we alsogot the gun code which caused it to all go wrong
Anyway, it does point to Fixed/Lateupdate and you don't really have much going on there, so start debug.logging those variables
something isn't being set and it's null
and when you're debugging values, make sure you debug left to right as you can't debug the dot operations if those too are nulll
so i did it again and my movement is somehow fine now?
could been that you didnt save the script
How do I make custom keybinds using unity's input system package
hello i am wondering how people handle back buttons for their menus using keys specially ( their no actually button on the screen menu that says back ) for sub menu navigation one example can be any rpg maker game where you let say you press the equip button then it highlights the which equips slot you want to use (weapon, armor, boots, etc) , then after picking the slot it then takes you to inventory where all the weapon are stored and you can pick from but you want to return to slot selection to pick a different so you hit the b key to go back to that one section like an undo key , i have heard that the command pattern can help with that but I've not seen if it is used for menus or how it would be
anyone see why it isnt reloading when i hitthe r key
videoim following
I present to you my longest video yet. Sorry for all the mistakes in the video, I usually don't make such long videos.
In this video, I teach you how to create a simple weapon system. In future episodes, we'll add weapon switching, and visual/sound effects.
PROJECT LINK: https://github.com/Plai-Dev/weapon-system/
Like & Subscribe!
Timestamps...
player shootcode
Is the StartReload() method getting called? Is the Coroutine Reload() getting called?
You can use
Debug.Log("Some Text");
to find out
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 5f;
public float jumpForce = 5f;
public float groundCheckDistance = 0.1f;
private Rigidbody _rb;
private Transform _groundCheck;
private Transform _cameraTransform;
void Start()
{
_rb = GetComponent<Rigidbody>();
if (_rb == null)
{
Debug.LogError("Rigidbody component not found on Player.");
return;
}
_groundCheck = transform.Find("GroundCheck");
_cameraTransform = Camera.main.transform;
}
void FixedUpdate()
{
// ... (rest of the script)
}
// ... (rest of the script)
}```
for some reason using a test project this code worked fine for wasd movement, but now it's in my main project it doesn't work at all
would someone be able to help me in the thread i made
"doesn't work" is too vague for us to help you.
Explain what you expect it to do, what it's doing instead, and any errors or logs you see.
also sharing the full script (in a paste site) would also be helpful.
why does he start some variables with _?
it's a common convention
well as I stated it's meant to be a wasd movement script, on the test project with the cube it all worked as should, moves all directions and forward is whichever way the camera was facing, but now It's in my main project it does, well nothing, theres no errors I have it all configured correctly in the inspector but alas nothing, no movement
in fact that's Microsoft's recommended convention for private members.
You need to do more debugging. First off - add logs to Start and Update/FixedUpdate to make sure they are running in the first place
Should I start doing that? Or is that some type of, "it don't matter how you do it."
You can do whatever you want.
Aight, thanks lad
so just add if (_cameraTransform == null) { Debug.LogError("Main camera not found."); } to the bottom?
??
No, add a separate log just to say "this code is running"
without an if statement
sorry that was the wrong debug code lol I'm getting confused between my camera script and movement script now 🤣
and no not "to the bottom", it should be the very first thing. We just want to see if the code is running at all.
Okay gimme a min or 2
Re/Hello 😄
I created a Toggle in a UIDocument, but nothing happens when I click on the checkbox. Did I miss something ? Ty ^^
what am i looking at here
idk I added the debug thing, i think the script is running but isn't working
added it where
show the code
I think I'm going to just re-write the script
you should learn to do basic debugging or you are going to waste a lot of time
why
there's no code there
Why the first condicional working, but the secund and third not working?
void FixedUpdate()
{
if (transform.position.y > 6.7f && transform.position.y < 7f)
{
Debug.Log("Shoot bullet");
}
if (transform.position.y > -4.2f && transform.position.y < -4f)
{
Debug.Log("Shoot bullet");
}
if (transform.position.y > -17f && transform.position.y < -17.2f)
{
Debug.Log("Shoot bullet");
}
}
considering they all log the same thing how do you have any idea which one it's going into?
public ChestAnimation chest;
RaycastHit hit;
void Start()
{
chest = FindFirstObjectByType < ChestAnimation >();
}
void Update()
{
InteractionRay();
}
void InteractionRay() {
Debug.Log(hit.collider);
if (Physics.Raycast(transform.position, transform.forward, out hit, 10f))
{
if (hit.collider.gameObject.name == "TestChest")
{
chest.Open();
}
else if (hit.collider == null || hit.collider.gameObject.name != "TestChest")
{
chest.Close();
}
}
}
I want to make it, so that whenever nothing or somethjing else is being looked at, chest.Close is called. Hit.collider is debugged as "Null" However it does not call chest.Close().
I haven't idea
Physics.Raycast returns false when it doesn't hit anything. What you actually need to do is:
- when you hit a chest, store it in a variable.
- add an
elseblock to the raycastifand close the chest there as well.
so why did you say "Why the first condicional working, but the secund and third not working?" when you have no idea if the first one is working?
what you should NOT be doing is chest = FindFirstObjectByType < ChestAnimation >(); - that is not helpful
get it from the raycast.
we want to know the chest your raycast hit, not any random chest in the scene
Hi, can anyone help with objects on different resolutions? Is there a code or a way to make the object automatically adjust to the screen size too?
Well, the first, secund and third condicional have the sentence, so, I don't understad that happening
if (Physics.Raycast(transform.position, transform.forward, out hit, 10f))
{
var chest = hit.collider.gameObject.GetComponent<ChestAnimation>();
}
Would you do it like this, or differently? Im asking because i do not know how to trigger certain methods like Open() and Close() if chest is not defined in the code. Should i use Interfaces for this, or am i mixing up something completely?
If it's UI then check the pinned documentation in #📲┃ui-ux to learn how to properly anchor and scale your UI for different resolutions
well you would need to use a member variable not a local variable because we'll need a reference to it later on
Not sure what you mean by "if chest is not defined in the code"
yeah so don't you think you should maybe make them print DIFFERENT sentences so you could start to understand what is happening?
and probably you dont need to raycast so far.. 10f..
50% or less would still be enough for most things... probably...
not much but still less performant... if you do that 100 times...
how do you know they're not working?
performance is really not a concern at the moment.
The distance should be whatever distance they want the game designed with
was just an advice.. if you learn it by beginning you learn it by doing
is it true that bigger distance worsens performance?
not always and certainly not linearly, but potentially, under the right circumstances, yes.
not much with the cpus today.. but if you do it 100x or 1000x times.. it will make a difference on the size of the scene and objects..
but a performance discussion here is really derailing.
yeah sry..
but if you start early its better ^^
but i think the problem as ssen i just cam back before.. is that chest is local and you call it from somewhere else..
try call it from somewhere else
so you need to make it available..from outwards
I try, but also not working
No, IDK
wdym by "not working". What did you try and what happened?
For now, print an message
Depend the position in axe Y
maybe do it with Update instead of FixedUpdate?
I meant show the damn code you tried and show what it printed andexplain what's happening in the scene too.
You're not going to get effective help here if you come back once every 20 minutes with a 3 word answer that doesn't explain what's going on.
private static Spline _perimeter; Spline is a struct, and I need to destroy the instance, but I cant write
private void OnDestroy()
{
_perimeter = null;
}```
what can I do to remove it?
Value types can't be null, best you can do is assign it default which is all of its bits set to 0
What do you mean by "destroy the instance"?
Structs cannot be "destroyed"
just so it doesnt exist after I stop playing
If this script is currently being destroyed (you're in OnDestroy) you don't need to do anything
it won't
Unless the struct is referring to some other thing, which would be the thing you actually need to destroy
You need to share more information here
we don't have enough context. What is this Spline struct? Where did it come from? Is it your custom struct? What fields does it have?
well setting it to default worked. It was just that when I stop running the game, I needed to make my static objects no longer exist
Again it depends what those things are
if this struct has a reference to, for example, a UnityEngine.Object instance, you would want to call Destroy() on that instance, for example
its fine with everything else, it was just the struct having the problem
It is not possible for a value type to "not exist"
because it's not possible for a field to "not exist", really
a value-typed field intrinsically contains the value (hence the name)
a reference-typed field just tells you where the actual object is (thus making it possible to have no object)
honestly, ive always found it a little difficult to know when to go with a struct or a class
I get the idea of structs
like when I've made my own Vector implementation in the past, its sensible those are always structs
i guess you should interrogate why you made it a struct
one obvious answer is "holy shit that'd be a lot of allocations"
making my Spline be a struct seemed like the right idea before
but that's a performance matter, and performance matters aren't satisfying
- Do you need to use reference semantics? class
- Do you need to create lots of little things frequently and discard them frequently? struct
yeah, class fits better for it
I suppose it'd be better to ask why you don't think you need a class
If you ignore things like being blittable (i.e. you can copy a struct directly into unmanaged memory and it'll still make sense), structs don't unlock new functionality
They just impose a bunch of rules on you
i just think of structs as simply data containers
And yeah, this is the big one: if you don't need reference semantics, you don't need a class
but that's a cop-out answer, I guess, because that's the entire distinction between a class and a struct 😆
if its not strictly just data i use class.. but then again im noob 🫠
intention when I first wrote it was that it belonged to my Geomety/Shape namespace, which are all structs. And it was always a very simple defintion it seemed like the good pick
It's shaped like itself
however a few things I was intending to do, ive decided against or figured out a better approach
Spline being a struct seems like its one of those things
also just noticed this is the beginner channel 😅
seems fitting to me.. i still consider myself a beginner.. and found value from reading thru it
Ok
using System.Collections;
using UnityEngine;
public class Enemy_2 : MonoBehaviour
{
public float speed;
public float points;
public delegate void UpdateUI(float points);
public event UpdateUI UpdateUIPoints;
Rigidbody2D rb2D;
[SerializeField] bool isMovingHorLeft;
[SerializeField] bool isMovingHorRight;
[SerializeField] bool isMovingVert;
[SerializeField] GameObject burst;
void Start()
{
rb2D = GetComponent<Rigidbody2D>();
isMovingHorLeft = true;
isMovingHorRight = false;
isMovingVert = false;
}
void FixedUpdate()
{
if (transform.position.x > 19.5f && isMovingHorLeft && !isMovingHorRight && !isMovingVert && transform.position.y > 1f)
{
rb2D.AddForce(Vector2.left * speed, ForceMode2D.Impulse);
}
else
{
isMovingHorLeft = false;
isMovingHorRight = false;
isMovingVert = true;
if (isMovingVert && !isMovingHorLeft && !isMovingHorRight && transform.position.y > -17.1f)
{
rb2D.AddForce(Vector2.down * speed, ForceMode2D.Impulse);
if (transform.position.y > 6.7f && transform.position.y < 7f)
{
Debug.Log("Shoot bullet");
}
if (transform.position.y > -4.2f && transform.position.y < -4f)
{
Debug.Log("Shoot bullet");
}
if (transform.position.y > -17f && transform.position.y < -17.2f)
{
Debug.Log("Shoot bullet");
}
}
else
{
isMovingHorLeft = false;
isMovingHorRight = true;
isMovingVert = false;
if (isMovingHorRight && !isMovingHorLeft && !isMovingVert && transform.position.y < -17.3f)
{
rb2D.AddForce(Vector2.right * speed, ForceMode2D.Impulse);
}
}
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "bullet_ship")
{
speed = 0;
UpdateUIPoints?.Invoke(points);
Destroy(gameObject);
Instantiate(burst, transform.position + new UnityEngine.Vector3(0f, 2.06f, 0f), Quaternion.identity);
}
}
}
Unless you've disabled domain reload you don't need to reset your static variables when ending the game. However if you have, you'd be better off setting it to whatever you had it set to before starting the game. Although if you never read it before assigning to it then it doesn't actually make much difference
A lot of this code doesn't make any sense.
isMovingHorLeft = false;
isMovingHorRight = false;
isMovingVert = true;
if (isMovingVert && !isMovingHorLeft && !isMovingHorRight && transform.position.y > -17.1f)```
What's the point of all of these bool variables? It seems like you are just setting them directly before checking their values. You can remove them completely in that case.
you KNOW isMovingVert is true and the horizontal ones are false because you literally just set them that way. THere's no point in having them.
ifTrue;
ifNotTrue;
ya, the bools instantly complicate things like simple if statements
mhmm, there was a really odd issue the other day when it came to domain reloading and my static objects not doing what they were supposed too
Fen helped out with it
Anyway, as I've been telling you many times, add more and different log statements at different points in the code to see where your code is actually getting to. You can also print the actual values of things, like the object position, to see what's going on @vocal orchid
Ok, I get it
it seems like the only thing you want to do in FixedUpdate is 2 things. either adding force, or to shoot bullets
that code will do that
but for a number of reasons, that code will be very tough to maintain
hehehe
void FixedUpdate()
{
bool enemyMustShoot = false;
bool enemyMustMove = false;
...
...
if(enemyMustShoot) { Debug.Log("Shoot bullet"); }
if(enemyMustMove) { rb2D.AddForce() }
}```
if you changed it to have a structure like this, it simplifies the way of setting up the conditions
if you ran this code, didnt have anything at the ... then it will never shoot and never move
the only goal is to find out what has to happen to make it do either outcome
Yeah, simply
Minimizing the amount of state is a great idea
Every field is something that can go wrong on frame X and then cause a problem on frame X+10000
I'm struggling with Local Co-Op multiplayer code. Specifically, item pickups (such as health, crafting materials, etc.) and each player's inventory. Anyone willing to give me a hand, let me know.
#archived-networking and probably give an actual question
Oh, unless you mean actual splitscreen co-op type of deal sorry
in that case, give the question here
Each player has an InventoryContainer Empty game object attached to them. Pressing Tab sets the inventory to active or inactive, and it has various slots to put items into.
I need a way to find out which player touched the Pickup, have the pickup reach out and talk to the inventory, whether or not it's open or closed, active or inactive, and then run the AddToInventory method.
I am having trouble:
- Detecting which player has touched the item.
- Getting that player's inventory, whether or not it is active or hidden.
For the player identity issue, you should have sort of collision detection or physics querying for each individual object that detects pickups directly. Each of your player instances should be unique, so knowing which of these characters touches those objects will be known inside of the object instance itself.
So far I've been using tags, and it's been working. The part I'm struggling with is mostly reaching out to that specific player's inventory.
Tags are not the way
Ideally you'd be handling the logic for picking up an item on the player instances so they should just have a reference to its own inventory
I see
Ideally, all the players would also being using the same exact code/script
you should not have like a "Player1Movement" script and a "Player2Movement" script, for example
The pickups are prefabs, and the name, count, and sprite are determined by a script attached to them.
I have that going on. Each player is a prefab, with identical code
Once the prefabs are in the scene, they are no longer prefabs.
Detect which player touched it with collision detection methods or physics queries such as raycasts/overlapXXX calls
what about OnTriggerEnter2D?
yes
that's a collision callback
you can use that
OnTriggerEnter2D gives you a reference to the collider you interacted with
you can get from that collider to any other components you want on that object with GetComponent
and/or traversing the Transform hierarchy as needed.
Then the other major issue; the inventory empty not playing nice with being active or inactive. even with OnTriggerEnter2D, it seems like the inventory being inactive makes it completely impossible for it to be found and communicated with.
Only if you're using FindWithTag for example
I even struggled getting this to work with just 1 player.
if you use GetComponent and/or traverse the transform hierarchy, it is not a problem at all
Really you just need a script on the root of the enemy that has a direct reference to the thing. Just interact with that one script.
I don't follow
Put a script on the enemy
when you collide with the enemy you grab that script and do whatever you need to do
void OnTriggerEnter2D(Collider2D other) {
if (other.TryGetComponent(out Enemy enemy)) {
enemy.ShowInventory();
}
}```
For example^
what is .TryGetComponent? I have never seen that in any of the Unity Tutorials I've been digging through.
it's just a more convenient way to do GetComponent and make sure the component actually exists
void OnTriggerEnter2D(Collider2D other) {
Enemy enemy = other.GetComponent<Enemy>();
if (enemy != null) {
enemy.ShowInventory();
}
}```
This is the same
Getcomponent brute forces getting a component, so if there is nothing there it will give you errors
I see. it's very clean.
yep
Anyone know how to use IK rigging to hold items similar to games like Lethal Company. For some odd reason when I have it keep the arms targeted to the item in the players hands if I look too high up the item falls off the hands.
so, when the player touches a Pickup, it talks to its own inventory.
The player needs to get information about what the pickup's name, count, and sprite. Should the player reach out to the item, then?
Whichever thing is handling the OnTriggerEnter would reach out to the other thing
As for which way the information passes, that's up to you
ok, so the player should be reaching, and the pickup is essentially just a text file full of info as to what it is. the player then copies that info into their own inventory.
that could work as a simple start, sure
the issue with the active/inactive inventory, OnTriggerEnter2D and TryGetComponent will still work if the inventory is inactive? IE, the player pressed tab so that their screen isn't covered by the inventory UI.
UI elements are totally unrelated to all of this
But yes, TryGetComponent does not care at all
about things being active or not
Most likely you have coupled your inventory UI too closely to everything else
No, no. the UI is causing no issues. It works beautifully. It's just that while it is inactive I couldn't get the InventoryController script on it, and tell it what item the player just touched.
but if TryGetComponent works even on hidden objects, it should have no trouble reaching out to the Inventory and talking to the script attached to it, even while it's inactive.
TryGetComponent won't find another object. so if you're trying to replace some FindXXX call with it, that won't work. You can call TryGetComponent on something you already have a reference to in order to get a component from that object you have referenced.
It also sounds like you have your dependencies backwards. Your Player shouldn't rely on the UI for the inventory, the player itself (or some middleman object) should control the inventory and the UI should just reach out to that to display what is in the inventory
How could I make my lighting actually dark? and my flashlight work a little better
thank you sorry
also make sure to provide more info such as the actual settings on your light
if i drop a GameObject on my main menu, and in its Start/0 I call Debug.Log(Input.GetJoystickNames()), I should see an array of strings of my joysticks, right? i ask because i bought some kit, and on their web demo the joystick works, but in unity editor it doesn't, despite that it looks wired up in the input manager, so i tried as mentioned and ... got an empty array. while using the joystick successfully in the web compile.
's very confusing
i even see reconnect and disconnect events in log for it. just ... not the controller in the name list.
seems unity was just having a brain issue. rebooted the machine and everything works as expected.
can anyone help me with a tilemap setting?
i want that the tile use only one slot instead of four or more
#🖼️┃2d-tools
But generally, I think that's controlled by the ppi(pixels per unit) setting of the sprite.
i tried that but i cant get the 1 slot tile
Does increasing the ppi by 2x not help?
You probably also need to reconfigure the tile in the tile pallet. I'm not entirely sure. Which is why you need to ask in #🖼️┃2d-tools
Hey I need help configuring my ide
!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
• :question: Other/None
nvm igot it
Trying to set up an inventory system from a tutorial, but he's starting from scratch and i'm starting from an existing project
This (image) is the code he has in the video, but I already have an interaction system in my game with Interfaces where when youre close enough to an object, you can press E to interact
I tried putting the tutorial code into mine (removed "other" as it didn't work with my existing code, but otherwise tried to follow the tutorial)
When I playtested, my object wasn't added to the inventory or destroyed. Anyone know how I can get back on track with the tutorial?
sorry I'm new to programming
{
IInteractable activeInteractable;
public InventoryObject inventory;
private void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
if (activeInteractable is Component activeInteractableComponent)
{
foreach (IInteractable interactableChild in activeInteractableComponent.GetComponentsInChildren<IInteractable>())
{
interactableChild.Interact();
}
}
else
{
activeInteractable?.Interact();
}
var item = GetComponent<Item>();
if (item)
{
inventory.AddItem(item.item, 1);
Destroy(gameObject);
}
}
}
public void TapInteractable(IInteractable newInteractable)
{
activeInteractable = newInteractable;
}
}```
After making this script my project froze and won't let me click anything on it what did I do wrong?
Took a photo of your monitor.
Too lazy to open discord on my pc
Can you help me or nah?
kinda hard to read. it's easier to post the code in the chat (for small code blocks) . . .
No. Take a proper screenshot if you need help. Or share the code properly as Random pointed.
also much easier for us to copy/paste and test it out ourselves, if necessary . . .
If I must
using UnityEngine;
public class burdscript : MonoBehaviour
{
public Rigidbody2D myRigidbody;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) == true)
{
myRigidbody.velocity = Vector2.up * 10;
}
}
}
That right or nah?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
But no, there's nothing in your code that might freeze or crash unity.
However, your !ide is not configured properly, which might be related to the issue:
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
for future reference, how many lines of code is considered "large"
yeah, nothing in here will freeze your editor . . .
It's fr just making the generic windows sound and it's frozen 😭
That depends. As much as it takes for it to be hard to read/extend/debug.
if it scrolls up the entire chat where other people's responses or questions get missed. pretty much, if it's more than a few small methods, use a paste site. when in doubt, use a paste site . . .
Add logs to see if the code executes as you expect it to. Or use the debugger.
in their code other is the interactable item. when they do other.GetComponent<Item>, they are attempting to access the Item MonoBehaviour (not sure what it derives from in the tutorial) from the object the player collided with. this is the same as you retrieving the IInteractable interface . . .
I started programming less than a month ago so I can't sight-read code yet
lol
I think I figured out what I did wrong tho, thx
how do i make it so the model rotates around the camera if that makes sense
so i cant see the body but other people can, because im making a multiplayer game
So I'm trying out a tutorial to make my first game. Its supposed to display the message in the console when hitting my obstacle (the black cube), but its not. When messing with the code I figured out its acting as though the player (red cube) is hitting the obstacle instead of vice versa. Someone please help...
By the last statement I mean that I made it at first where it would display the name of what object the player hit, and instead of it displaying "obstacle" it displayed "player"
Its messing my code up entirely
is the script on the player or the obstacle
Elaborate?
Sorry I'm slow ;-;
Oh, wait, I think I understand
Its on the obstacle
OMG NVM I GOT IT TO WORK I FEEL SO DUMB
The project is still frozen, ion wanna lose it so what should I do?
yall is the OnMouseDown() method an individual method or is it part of one of the input systems?
😭 its okay
99% sure its individual
got it thanks
Not really sure what this question actually means but afaik it only works when using the old input system
so it is part of the old input system?
Not exactly
and what i meant was if its a individual method not linked to any input system
What's the actual reason/motivation behind the question?
It's not part of the old input system but it only works with the old input system, is my understanding
watching a tutorial and they used OnMouseDown() and i wanted to know if it was part of the old input system since the whole course uses the old input system and im getting used to using the new one
i see
ill have to investigate alternatives for that then
OnMouseDown is effectively replaced with PointerDown/IPointerDownHandler which are part of the UI system.
(but still work with non UI objects)
seems fair
just need to delete a game object so its gonna be simple
thanks
and happy new year
Hey Everyone, quick question: I'm trying to create a waypoint system for my 2D game, here's my current working code with a minor issue.
{
if (playerTransform == null) return;
float maxScreenX = Screen.width - screenMargin;
float maxScreenY = Screen.height - screenMargin;
Vector2 pos = Camera.main.WorldToScreenPoint(targetTransform.position);
pos.x = Mathf.Clamp(pos.x, screenMargin, maxScreenX);
pos.y = Mathf.Clamp(pos.y, screenMargin, maxScreenY);
transform.position = pos;
}```
this doesn't represent well if my target is offscreen. let me explain, if my target is offscreen to the right and slightly upward.. (think of it as 2:00 on a clock) the waypoint should not be representing the icon at 2:00 on the screen border, instead somewhere between 2:00 and 3:00 since 3:00 is the center of my character in the horizontal direction. am i making sense ?
i can draw a simple picture if this doesn't make sense. let me know thanks!
i made the picture anyway. i want the waypoint icon to show on the green 'X' not the red 'X'
I just wanna present a game idea to someone
hey guys! what you guys are seeing here is two box colliders, i dont want them to overlap and i want the outer hitbox to not overlap the inner hitbox (i hope it makes sense)
im not sure where to post this, but any help is welcome!!
You could maybe represent the screen as Bounds and get an intersection of your vector with the bounds. That would be your green point.
You can't really not make them overlap. If it's an OnCollision/TriggerEnter that you want to not be called inside the small box, them you'll need to handle it in code.
so like, the inner hitbox has a different audio to play, and the outer hitbox plays kinda like a terror radius
You could use Bounds for the internal area and check if the character is in the bounds in one of the updates, or OnCollision/TriggerStay
bounds?
what is bounds? is that a screen property?
Why not just cover the outer area with 4 colliders ?
just figured there was a more efficient way to do it, i did think about that though
The performance of calculating if you are in the big volume while also inside the small volume is arguably going to be worse
you think so? mm, ill try that out, thank you!
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
@compact stag
It's just a struct with some utility methods making it convenient to deal with bounds.
Check the documentation.
guy can you tell me why both code got active? even tho i make a bool that make sure that both of them won't get active at the same time.
if (Input.GetKeyDown(KeyCode.Q) && cursorLock == false)
{
Cursor.lockState = CursorLockMode.Locked;
cursorLock = true;
Debug.Log("lock cursor");
}
if (Input.GetKeyDown(KeyCode.Q) && cursorLock == true)
{
Cursor.lockState = CursorLockMode.None;
cursorLock = false;
Debug.Log("unlock cursor");
} ```
also i putting it on void update
Its Update.... so it's called multiple time per sec...
So during each call diffrent if statement is totally true, and its look for you like both are called
then i have to place it on void start?
Input need to be on update
Cause you need to detect user input
Maybe add "else" before sec if?
ok
Use an else if.
If you enter the first if statement currently, it'll change the condition so that you'll enter the second if statement too.
ok
it still execute both of them
if (Input.GetKeyDown(KeyCode.Q) && cursorLock == false)
{
Cursor.lockState = CursorLockMode.Locked;
cursorLock = true;
Debug.Log("lock cursor");
}
else if (Input.GetKeyUp(KeyCode.Q) && cursorLock == true)
{
Cursor.lockState = CursorLockMode.None;
cursorLock = false;
Debug.Log("unlock cursor");```
at the same time
It's not at the same time, you changed it to GetKeyUp
I would like to attach a script (i need the class inside) to a scriptableobject,
but monoscript is only available in unity editor not in runtime,
is there any way to attach a script to a scriptableobject?
Sounds like there's a bit of conceptual misunderstanding there. You don't need to attach scripts anywhere to access classes.
does TilemapRenderer have a way to flip their full sprite(s) horizontally/vertically like normal sprite renders? flipX and flipY dont exist for them
https://paste.mod.gg/jvyjpbwpkens/0 can someone help me figure out why my jump isnt a consistent height? Sometimes it jumps higher other times it jumps lower 
A tool for sharing your source code with the world!
try using velocity instead of linearVelocity
Commenting out the line rgPlayer.linearVelocity = new Vector3(rgPlayer.linearVelocity.x, 0f,rgPlayer.linearVelocity.z); pretty much fixed the problem, still a bit inconsistent but its much less noticeable now 
if (elapsedTime < duration)
{
elapsedTime += Time.deltaTime;
float t = elapsedTime / duration;
float x = Mathf.Lerp(startPosition.x, endPosition.x, t);
if (Mathf.Abs(transform.position.x - vertexX) < 0.1 && a == oldA)
{
a = (endPosition.y - vertexY) / Mathf.Pow(endPosition.x - vertexX, 2);
}
float y = a * Mathf.Pow(x - vertexX, 2) + vertexY;
currentPos = new Vector2(x, y);
transform.position = currentPos;
}
Guys im trying to make a parabolic motion and this is what i got but the object doesnt go to the end position it parabolically goes somewhere else
It's obsolete, don't use velocity
Hello!
So I'm currently trying to finish Unity Essentials Pathways but kinda stuck on the last task which asks you to make a script that plays SFX when Blocks/Ball interacts with each other.
My block script works well, but ball SFX doesn't work for some reason. (2nd pic)
Any thoughts?
you are comparing for the same tag on 2 different objects, is this correct?
and why would you compare tag on the object that these scripts are attached to
additionally to what steve said, you need to use if(collision.CompareTag("tag"))
did you not get any error messages
Uh, sec
I did not. So, the idea was (seeing what was similar to Essentials Pathway), I decided to compare the tags, so for example, if something collides with blocks, they will make a sound. And since they are being knocked over by the ball, when they collide with each other, script checks it and plays sound
For some reason even if there is no block nearby and player touches one of the blocks, it still plays that sound, I have no glue how it works so perfectly
but you are not checking what is being collided with
How can I do so?
#💻┃code-beginner message
As you have been told
In pathway I saw (other.CompareTag("code lala"), but it does not work, why is that happening?
Gives me an error
because you do not have a variable called other you have called it collision
please don't tell me you just copy/pasted that
I wrote what he said 🥲
try using your brain
That's the same thing as if you said to a lawyer to launch a spaceship
no it's not.
you were given some example code, it's up to you to make it work with your situation, that is the nature of writing software
Uh. So, in the script they provided, that variable is being accepted by the system, but in my situation, for some reason not.
That's what I'm trying and kindly asked for some help, not just "try using your brain".
notice how they have a Collider (because they are using a trigger) and you have Collision
2 different objects, 2 different requirements.
Go read the Collision docs and see how to get to an object which will accept a CompareTag method
Does it work only with Collider?
hint. Collider is a Component. Collision is not, so you need to get a component reference from the collision
Alright, I will search the docs, tyy
Well, I fixed everything and it works perfectly, so.. Is that CompareTag thing was so that important? Like OnCollisionEnter works good itself, all you need is to just play sound?
And no need to see if it was a player or block, it will collide with everything.
hey, I've started learning unity few days ago, (have some background as c# dev) rn during making the 2d game, I'm on really early stage (like player character movement + attack with few animations), and even now I'm getting feeling like my code is starting to be spaghetti, do you have any tips how to keep code clear/some guidelines/done projects that i should refer to when designing code structure?
How do I regenerate the #C project/solution files ( Unity 6, 6000.0.32f1, LTS ) ?
I don't understand this question
The example code uses CompareTag to decide if we just collided with something with a tag of "Player"
If you don't care what you collided with, then I suppose checking its tag is no longer relevant
any reason why the rawimage doesnt enable when looking at the object with the tag?
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.
have you checked what you're actually hitting with the raycast?
line 26 in that method is a closing curly brace
so I don't think the code you sent matches the code you're running
prompt.enabled = true;```
thats line 26
i did update the code but it didnt work
void Update()
{
RaycastHit hit;
Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range);
if (hit.transform.CompareTag("Ladder"))
{
Debug.Log(hit.transform.name);
prompt.enabled = true;
}
else
{
prompt.enabled = false;
}
}```
could it be bc theyre prefabs (its a multiplayer game)
Click on the error in the console once while the game is running
This will highlight the object in the hierarchy
Perhaps you have multiple "Raycast Testing" components in your scene
(or perhaps the reference is missing from the one that actually exists)
i fixed it that error it was because it was scanning every single thing, i just changed it to scan for ladders
How do I program a fade in for UI text? Like using fill amount for images basically - I've tried incrementing the maxVisibleCharacters steadily, but it's not quite the effect I want
but the problem was clearly that prompt was null
oh
hence the error coming from that line
Hi, I'm trying to create a computer screen in my game. My problem is I can't click the icon (in world space). Didn't know what settings I messed up.
At the bottom of the inspector for the event system it should show you info about what object you're hovering over. If some of the things can't be clicked on but others can, it's most likely the case that something else is "in front" of them as far as the event system is concerned. See what object the event system thinks you're hovering over when you're trying to click an icon
I checked the bottom of the inspector. It's always the same object.
ah, you don't get much information out of it when using the new input system
(i have no idea why)
I don't think you can easily get this information out of the EventSystem directly, either
it has IsPointerOverGameObject, but that doesn't tell you what it's over
Maybe some UI are sitting in front of those icons. I created another button in the world space, and this btn works fine.