#💻┃code-beginner
1 messages · Page 262 of 1
🤿
also i need to seperate my movement script into smaller scripts for each function like leaning crawling etc
cause its at 2032 lines
and im like 2/3 done
help, i'm doing a movement script and i tried making jumping possible, but when i press space the boolean for "isJumping" doesn't mark as true, help: ```csharp
using JetBrains.Annotations;
using System;
using System.Collections;
using System.Collections.Generic;
using TreeEditor;
using Unity.VisualScripting;
using UnityEditor.UI;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController control;
public Transform groundCheck;
public float speed = 12;
public float gravity = -9.81f;
public float checkDistance = 0.4f;
public float jumpForce;
public LayerMask groundMask;
Vector3 velocity;
public bool isGrounded;
public bool isJumping;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, checkDistance, groundMask);
if (isGrounded)
{
isJumping = false;
Debug.Log("Grounded.");
}
if (isJumping)
{
isGrounded = false;
velocity.y = jumpForce;
isJumping = false;
}
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
if (isGrounded && Input.GetKeyDown(KeyCode.Space))
{
isJumping = true;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
control.Move(move*speed*Time.deltaTime);
velocity.y += gravity * Time.deltaTime;
control.Move(velocity * Time.deltaTime);
}
}
damn, that be long . . .
nvm i think i see what happens
https://hastebin.com/share/nozufuwizo.csharp can i make the entire string/text thing but with tmp?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
how can i*
the same exact way but use TMP_Text
https://learn.unity.com/tutorial/working-with-textmesh-pro
how can i achieve goldensrc's movement mistakes in such a way to get bhopping?
like on hl1
sure
nvm
might help to say or reference whom goldensrc is . . .
Okay. i have a problem my code is stuck at waiting for the OnJoinedLobby() callback when hosting a lobby. i dont know what is going on! HERE IS CODE: https://paste.ofcode.org/GBjeh9FPhAcb5tQ7ZRi4Ru i know im sopossed to be in #archived-networking but its dead soooo dead!
thanks
goldensrc is the game engine used in half life 1, which leads to very bizarre movement
thats where bunnyhopping comes from too
i dont understand it
Input.GetKey
damn
Explanation of how the player movement code in Quake gives rise to these three different player movement "bugs", with a quick look at TAS movement mechanics at the end.
Big thanks to the Quake Speedrunning Discord for helping me out with getting TASQuake running on my machine, and for clarifying terminology.
Here are the original C versions of...
hmm i cant really find a good solution out of the top of my head other than hard-setting the y velocity once you reach the top + hold the up key 😄
heldItem = Instantiate(slots[currentSlot].GetComponent<InventorySlot>().slotItem.GetComponent<Item>().heldItemPrefab, heldItemLocation);
why is this line throwing this error? It looks fine to me, but it seemingly has an issue with how I'm using GetComponent
what is slotItem?
a gameobject
make sure its not null or destroyed
oh wait, it looks like your usings at the top import the wrong stuff
is there anything in there about visual scripting?
yeah, which I'm not using
then throw it out
idk why that's in there
its overriding your GetComponent
How would i be able to assign more then one gameobject to this script ```cs
public class PlayerInteractUI : MonoBehaviour
{
[SerializeField] private GameObject containerGameObject;
[SerializeField] private PlayerInteract playerInteract;
[SerializeField] private TextMeshProUGUI interactTextProUGUI;
[SerializeField] private Transform playerCameraTransform;
[SerializeField] private LayerMask pickUpLayerMask;
public ObjectGrabbable objectGrabbable;
private void Update()
{
float pickUpDistance = 2f;
if (playerInteract.GetInteractableObject() != null && (Physics.Raycast(playerCameraTransform.position, playerCameraTransform.forward, out RaycastHit raycastHit, pickUpDistance, pickUpLayerMask)) && objectGrabbable.Grabbed == false)
{
Show(playerInteract.GetInteractableObject());
}
else
{
hide();
}
}
private void Show(IInteractable interactable)
{
containerGameObject.SetActive(true);
interactTextProUGUI.text = interactable.GetInteractText();
}
private void hide()
{
containerGameObject.SetActive(false);
}
}
make another game object variable
I want to to be all object that are able to be picked up
well that's a bit more work
😦
you seem to have the layers and raycast going so I assume you've the idea, no?
yea i tried using a tag on the objects that can be picked up but i couldn't seem to figure it out
not layers tho
your video shows you using two cubes
nvm i have a layer called pickup/down
damn that first person view is SEXY
what do you do for it? just rotate the camera according to the horizontal input?
u mean the side rotation?
yeah
i've been meaning to learn smoothdamp operations but i haven't gotten around to it yet :/
trying to get all the math in my brain
im thinking to not just add force up
but the closer he gets to the surface
to add more force down
and less up
and vice versa
well you already have the 9.81 gravity downforce constant that you are basically diminishing by adding an up force
if you add 9.81 up every frame you end up with 0 acceleration
i apply extra gravity as well
have thought of adding a buoyancy value?
how do i change the height of my character inside the scripts?
inside which scripts
like the height of what they will collide with?
like on code
or the actual physical height
accesing the scale of the transform thing
the physical height
i thought transform.scale existed
take my advice with a grain of salt
i’ve seen it
and people use drag for it
which is cant modify
cause it messes with other things
but i would make a variable that saves my character's height in the void Start() section
at least from the videos i’ve seen
then a transform.Scale() function with the parameters of your height variable
man idk i dont really like using the void start() section
all i need is to modify the height for crouching
its not that hard lol
are you trying to adjust the height of your collision box?
no, like the player body height
or if someone smarter than me could help me out, would you have to adjust the collision box or the size of the Rigidbody
i’ve decided im going to implement my own drag logic
do it
just for y velocity
which is really easy to do
from what im seeing
its literally just this
yeah what are you thinking for the math?
the drag will do the job
because it worked before
Vector3 target = Vector3.Scale(transform.forward,new Vector3(0,0,-1));
Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
Is someone able to explain why this doesn't work and point me to an appropriate method of handling this. This is in an empty gameObject script and just needs to move the gameObject backwards on the z axis
but it also messed with horizontal movement
thats why i’ll just make my own just for vertical
anyway im about to hit the sack
so i’ll do it tmr
oh wait I need to do transform.postion = dont I
what are you trying to accomplish
Vec3 Move towards return a vec3
yeah ok its moving (in the wrong direction)
It doesn’t change your transform
but its moving now
move a gameObject on the world space z axis it is aligned with it so moving towards the world or local will work
lemme try smth
apparently charactercontroller can adjust the height, i just had to assign a cc
ok well its moving in a diagonal in the oppsite dir than I want
this scales your forward vector so that its Z component is backwards and its X and Y components are zero
then it tries to move your position towards this vector
which will be a very short vector between [0, 0, -1] and [0, 0, 1]
then you throw the result out
if you assign that to your position, you'll move towards that vector
but that still doesn't make much sense
i havent used charcontroller in a minute lol i never would have guessed
wait
You are moving to a direction not position
do you want to move it in the +Z and -Z directions?
yes
add that direction vector to your position to get a target
i want the position behind the gameObject
ah ok
well, just do transform.position -= someVector * Time.deltaTime * speed;
that's just -transform.forward
scaling it by [0, 0, -1] is throwing out the X and Y components
so it only moves in the world Z direction
transform.forward is a world-space vector that indicates what "forwards" is for you
you can't get rid of the X and Y components from that and expect it to still be "forwards"
Scaling it by [1, 1, -1] would also be wrong
can u guys help me
I can when it's world aligned with z...
why not just do it correctly?
instead of writing code that only happens to work in a very specific scenario
i find it weird it lets me use a negative on a vector 3 like that
- is the unary minus operator
it's used to negate a value
there's no transform.back, hence the need for this
he means, just ask your question. don't ask if you can ask, to ask and ask
yeah but I mean like in a practical situation using a negative in front of what is essentialy an array is just sorta not smth I'd think of naturally
is what I mean
Vector3 is not an array.
idk whats up witht he code
just making sure 🙂
What is the issue?
and this kind of thing is extremely common
it was working fine about a while ago, now the camear is ahead of the character
its formatted like an array yes ik its a seperate type
you do lots of vector math in games
target.position - transform.position
surely that isn't weird
what i want to happen is the camera follows the player as it moves, the issue is that the camera is ahead of the character and moves in the direction where the player is going
i dedeuced that its obv just coordinates off but idk whats up in the code
Seems like the pertinent code is not showing . Post the whole thing
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
And also, obligatory "use cinemachine"
I'm gonna be brutually honest ik I'm doing stuff wrong but I feel I'm getting some simple concepts explained to me like I have 2 iq and it doesn't feel nice
Try moving the camera movement into late update.
ok
You expressed confusion, so I provided some more information.
Yes there is, you just have to write the word 🤷♂️
Just like you did Update and FixedUpdate
just like .. I know a negative makes things negate lol. God I hope I do at least otherwise I might wanna get out of college calc ASAP..
Sorry
I wasn't trying to come off agressive
I just felt a bit attacked for a second
I figured you might not have been familiar with how the - operator works. It's usable with quite a few things, not just floats and ints
amusingly, there's also a unary + operator
It calls operator overloading and you can find the operators of vec3 in docu
Stick around this server a bit and you'll understand that we don't know what you know, and can never assume
I mean I didn't know that - and + were used as operators on Vector2s and 3s and that is helpful yes
I mean
fair
we stiull have the bug
anyway, yeah, -transform.forward will give you the direction that's "backwards" for transform
Just one of my pet peeves I need to work on a little
(you could also do transform.TransformDirection(Vector3.back) if you wanted)
yep I fixed it
In this case, we're interpreting Vector3.back as a local-space direction
and using TransformDirection to turn that into world-space
Vector3 target = -transform.forward + transform.position;
transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
I did this
(that's what transform.forward is doing, just with Vector3.forward!)
Also, rather than creating a target, it'd be better to just do
transform.position -= transform.forward * speed * Time.deltaTime;
Why not just make the camera a child of the player?
Or look into cinemachine
If your speed is high enough to move at more than 1 meter per frame, this code will move too slowly.
since target will only be 1 meter away from transform.position
I see what you mean
camera on easy-mode
has tons of built in functionallity
and comes built-in to unity
@swift crag Thanks
how do i access cinemachine
i looked through package manager
ill do this tmrw ig
It's in the package manager. The docs are pinned to #🎥┃cinemachine
Can I set up an OnTriggerEnter2D to only work with for example CircleCollider2Ds and no other type of colliders?
when you get a callback check if the collider is of type circle
Nevermind, there's actually an option to exclude certain things on layers in the collider option
yup, but remember there's only so many layers
i've never ran out.. but ive gotten close lol
public void fireRay()
{
Ray ray = new Ray(transform.position, transform.forward);
RaycastHit rh;
if (Physics.Raycast(ray, out rh))
{
Debug.Log($"hit:{Time.time},{rh.transform.gameObject.name}");
}
}
So the code above works when I use apply it to the 2D non-UI pink diagonal square that is in front of the white square. However, when it is applied to the UI version of the two squares, it does not work. How can I make that work for the UI objects?
you need to use a raycast specifically for the UI
Physics raycasts are for the scene
or well, the non-ui part of the scene ;)
thank.. i think i will find something that it for nonui
there's a few ways you can grab what's over the mouse on the UI, usually through the event system interfaces or calls
Is Unity ECS and Unity DOTS the same thing? Can you use one without the other?
a lot of examples i found deal with the mouse position, but i see your point. my application is for games that move an object, for ex a square so it does not necessarily a point and click
I can substitue the mouse position with the position of the square in that case i guess
well, you must be doing input somehow
DOTS referes to several systems/packages: jobs, burst compiler and ECS.
keyboard keys.. u,l,r,d
Data Oriented Tech Stack iirc
Ah, probably can use screen position to ray method, but I'm not too sure beyond that
actually, that is another possible option. i like to consider many, thank.
maybe something like getting the canvas, and since it cover every gameobject in view, maybe i can launch rays all within canvas bounds
When I try to play my game, it would load to 90%. Is it an issue with the WebGL? It has ever done that with me before when I publish games
try a different browser..
a lot of webGL games i try to play stall at 90%
and then they'll work in some other browser.. not sure why tbh maybe someone knows
i see alot of people mention trying to change the compression
I have tried a different brower and its still happening. I have shared my Web link with my professor and my classmates and they are saying that the load is still suck on 90%
Thank you so much for the link
np, changing the compression usually works for me
Hi all, I am wondering why i have this pink line when i am creating my drawing mechanic for my game.
is it to do with the code or should i ask the ui page
(Forget about it fixed it..)
Pink usually means that the used shader is incompatible or broken.
I relised that the line was too big when it is saved and that i need to have the line renderer keep the same size as well as having the material copy to the new object.
(I am not the best writer sorry)
Mao, I solved the graphics raycast problem by converting the GO position to canvas coordinates, eg RectTransformUtility.WorldToScreenPoint(), so thank again. it replaced the mouse position
Are there any situations where Screen.width and Screen.height will not match the current resolution of the window/screen?
I'm currently using Screen.width/height to get the resolution, using it as a variable in UI adjustment calculations, and it seems to be working perfectly in editor, but I understand some things behave... Incorrectly, in runtime, as compared to editor.
Can anyone give me a brief answer to when should I use mono behaviour and when not and when I don't use mono behaviour how does it work please
Ping me on reply
When you want it to be a component, you use a MonoBehaviour. When you don't, you make it a plane class.
Will I find any documentation bout this with examples and details of working with normal classes and mono behaviour
You can lookup MonoBehaviour in the documentation, but there isn't really anything on plane classes. You'd use them the same as in any other C# app.
Oh okk thanks so much ❤️
Hello,
So I have these rockets and I want them to chase and hit the enemy(which is an array of multiple gameobjects), the rockets chase the enemy but not directly it like hovers the enemy instead of hitting it directly.
Any help is appreciated
``public class Rockets : MonoBehaviour
{
private Rigidbody RocketRb;
// Start is called before the first frame update
void Start()
{
RocketRb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
GameObject[] enemy = GameObject.FindGameObjectsWithTag("Enemy");
foreach(GameObject adui in enemy)
{
Vector3 enemyDirection = adui.transform.position - transform.position;
RocketRb.AddForce(enemyDirection.normalized*10);
}
if(transform.position.y <-1.5f || transform.position.y > 1.5f || transform.position.z > 15 || transform.position.z <-15)
{
Destroy(gameObject);
}
}
}
``
What exactly do you mean by "hitting"? Are you referring to the rocket being destroyed?
Colliding, because I have Rigidbody setup it endsup pushing the enemy.
If it's pushing it, then it's colliding.
Yes.
Anything else beyond that you'd need to code
I would like for the rockets to chase and hit the enemy, but the rockets chase the enemy and not actually hit but hover over the enemy.
You said that they push the enemy..?
Yes, they push the enemy but after hovering over the enemy first. But I would like for the rocket to hit directly.
hi! how can i make a gameobject go to a certain side depending on its rotation? i´ve tried with transform.up but idk if im making a strange approach to the problem
the switchs makes it so that depending on which bullet it is, it either goes left or right
omg.. today i learn playerprefs dont have getbool.. 
how's this for an autosaving setting system?
good enough?
oh i can edit the getter to have default value
Can you record a video of the issue?
Yes, here it is.
how reliable is using transform.lossyScale? At what point will it usually start to skew?
Hi, is it possible to expose the constructor of a class to the inspector like you would for a standard field? See the constructor where I would like to have the option of specifying an f, z, and r from the inspector of a PlayerController class which are private fields inside SecondOrderDynamics.
No
One of the many reasons to avoid PlayerPrefs
You can make a Property Drawer that converts whatever fields you draw in the inspector to whatever values you want to serialize. But you cannot call a constructor from the serialization system.
Also, this is a question for #↕️┃editor-extensions
Mmm, ok thanks and sorry about the chat.
Can you debug the number of enemies you get with the find?
I think the debug shows the enemy number correctly, it shows that there is one enemy and after enemies increase in increase on debug.log as well. So basically it works fine.
Does it work correctly with only 1 enemy?
Nop, here is a video.
Remove the using System.Numerics line
oh okay thanks
Using
RocketRb.velocity = enemyDirection.normalized*20;
instead of
RocketRb.AddForce(enemyDirection.normalized*20);
Fixes the issue of hovering and the rocket chases the enemy and hits it directly without hovering.
Thanks.
!vscode
I have no clue what I am missing
This error is tied to a script / series of scripts from what I can tell( Inventory System, Item PickUp System and the Item itself ). This error appears everytime I intereact with my interactable object. The scripts are meant to pickup the object, delete it from the scene and make the itemcount go up ( +1 for each item picked up )
The errors are simple: null reference. Do you understand what it means?
Not quite, did I not drag something onto a asset in the inspector tab?
Perhaps.
Do you understand what a reference and null are?
Isn't a "reference" refering to a method that calls a certain script within it?
I'm guessing null has it's general meaning of a nonexistent value / object ?
No.
A reference is referencing an object.
I strongly recommend going through the C# basics before continuing your project.
Yeah, that's closer to being correct. Still, recommend going through the C# basics first. As well as learn a bit on object oriented programming.
im making a game thats pretty much just a dropper map, but the players speed increases as they fall, is there a way to 1.control the rate at which said speed increases and 2.make “power” that lets them break momentum
Can I find one on the Unity Forum?
Yes. There's almost nothing impossible with coding.
- Change the gravity value.
- Not sure what you mean.
There's a beginner programmer pathway on unity !learn. Then there's the Microsoft C# manual.
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I'll look into them right now. Thank you!
how does one go about changing the gravity rule and i think ive figured out the second part now (tho i realise the way i explained it was silly lmao)
Hello, uhmm are there any video guides to properly learn how to use unity and proceed to asprite -> unity interface etc.
If it's coming from physics, then you can change it in the physics settings manually. Or via code. There's a property in the Physics class.
Ohhh thank youuuu
In development at Unity is a 2D Animation package that allows you to rig Sprites as one might rig a 3D model for animation. In this tutorial, you will go through the process of importing the 2D Animation package and rig a sprite ready to be animated. You will learn about all the features of the 2D Animation package, including Bones, Weights and ...
thankkk youuu
What would be the proper class to use so I can simply pick an action from my input master?
Ah found it: InputActionReference
I'm about to start working on ai for a stealth game, so they'll do the classic patrol, investigate, search etc. I've been looking into finite state machines and have just heard about behaviour trees. They both seem to have ups and downs but I'm not too sure when you'd use either one. What are the pros and cons of each and how would I go about deciding which to use?
My character can phase through walls if you walk into them for long enough
I use transform.Translate for movement
How can I prevent him from doing that?
Don't use transform.Translate, it does not respect physics
{
// Create fireball at the character's position
Vector3 bulletSpawnPosition = transform.position + new Vector3(0f, 1.5f, 0f);
GameObject bullet = Instantiate(bulletPrefab, bulletSpawnPosition, Quaternion.identity);
// Calculate the direction towards the mouse pointer
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity))
{
Debug.Log("Hit point: " + hit.point);
Vector3 bulletDirection = hit.point - transform.position;
bulletDirection.y = 0;
// Apply the direction to the fireball
bullet.GetComponent<Rigidbody>().velocity = bulletDirection.normalized * bulletSpeed;
}
}```
the bullet is not moving, any fixes?
Log bulletDirection.normalized * bulletSpeed and see what it returns
https://unity.huh.how/debugging/logging/how-to
Then log bulletSpeed and notice it's probably 0 because you did not set it
Vector3 bulletDirection = hit.point - transform.position;
should be
Vector3 bulletDirection = hit.point - bulletSpawnPosition;
?
{
Debug.Log("Hit point: " + hit.point);
Vector3 bulletDirection = hit.point - transform.position;
bulletDirection.y = 0;
// Apply the direction to the fireball
bullet.GetComponent<Rigidbody>().velocity = bulletDirection.normalized * bulletSpeed;
}```
this is not getting called apparently
The if-statement is not called? Or is the Fire() method not being called in general? You can place a log message at the start of the method to test this
Don't tell me, AI fucking code, again
fire() is working, the physics raycast aint working
Did you write this code or did you let ChatGPT write it?
no clue, aint mine to begin with
this is a doubt from junior and even i am unable to fix it
T_T
Perhaps try drawing where it casts a ray?
https://unity.huh.how/debugging/visual-debugging
https://unity.huh.how/debugging/draw-functions This specifically
Whatever it casts to is clearly not what you'd expect
there is absolutely no logic to that code, so obviously AI generated
then i wont help him then, ez XD
tell him to learn to actually read code and understand what it does
gotcha
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Sup! im trying to make random generator (cubes only, but it doesnt work properly (see image), can someone help?
void Generate()
{
float spaceBetweenSections = 3f;
Vector3 spawnPosition = Vector3.zero;
Vector3 prevSize = Vector3.zero;
for (int i = 0; i < numberOfSections; i++)
{
System.Random random = new System.Random(seed.GetHashCode() + i);
GameObject selectedPrefab = sectionPrefabs[random.Next(0, sectionPrefabs.Length)];
Instantiate(selectedPrefab, spawnPosition, Quaternion.identity);
spawnPosition = Vector3.right * (prevSize.x / 2 + spaceBetweenSections + prevSize.x / 2);
prevSize = selectedPrefab.transform.localScale;
}
}
Fixed rn by destroying first instantiated object
No i didnt fix..
alr, i fixed by asking chan gpt..
why don't you try fixing things yourself? You might actually learn something
well, i tried, and stuck for 30 mins, with chat gpt i can fix things faster, but i also read all code to make sure that i wont get same mistakes in feature
actually learn something
I would not even learn code if i didnt used tutorials and gpt
I don't know where you got that code from but 90% of it makes no sense
I don't care, it works, all what i need, i may change it soon
Don't 
hi guys! I`m doing a coop game, I put animations on characters, but when moving them shakes. I added a virtual camera and its gone, but in the second player it just goes off. Can someone help pls?)
cant understand anything from the sentence
So i want the cyan circle to rotate around my player, but it does some weird stuff instead?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TEMP_WEP : MonoBehaviour
{
public GameObject weaponPrefab;
public GameObject player;
void Update()
{
weaponPrefab.transform.RotateAround(player.transform.position, Vector3.up, 150 * Time.deltaTime);
}
}
virtual camera just off when in session spawning second player
ok wait vector3.forward works kinda, it circles properly, but the spacing between me and the cricle increases if i move?
Right. You're telling it to rotate around a moving point
That's different from following a moving point and then rotating around that
Imagine a circle centered on the player and that touches the item
If you move further away from the item, the circle gets larger.
If you want the circle to spin around the player, I'd suggest first moving it so that it's the correct distance away from the player, then using RotateAround
also, if you want it to spin around the player in a circle, use Vector3.forward
Vector3.up means it's rotating into and out of your screen
yeah i got the vector3.forward
will try this
To get the correct position, consider doing this
Vector3.MoveTowards(player.transform.position, transform.position, desiredRadius);
MoveTowards is useful for more than steady movement!
Although, actually, I guess it's not the best choice here...
since it won't move the item further away from the player, right.
(transform.position - player.transform.position).normalized * desiredRadius + player.transform.position;
that would be more appropriate
could not hold myself from ranting: Could scrollbar be more bugged?
the Unity UI scrollbar?
ScrollRect is decently complicated; it's easy to set it up wrongly if you don't just use the template from the GameObject menu
i guys can someone help me to find a good programmer to make me a 2d game roguelike?
!collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
thanks
yeah, this shame here
The GameObject > UI > Scroll View template works well. I did have to add a couple of things to Content:
- A ContentSizeFitter set to "preferred size" on both axes
- A VerticalLayoutGroup set to control child size on both axes (and to not force-expand children)
If you're having problems with Unity UI, you should ask about it in #📲┃ui-ux
when the second player appears in the session, the virtual camera is destroy in all clients, help plsssssss
How do i save an asprite file then transfer to unity?
ask your question with more details, noone is going to help you if you dont even try to provide what is wrong exactly
this is a code related channel
google/search how to import a sprite into unity. anything else, i'd ask in #🖼️┃2d-tools or #🔀┃art-asset-workflow
oohh okay thanks
hey guys. im working on the NPC dialogues, and i have this piece of code:
public class PlayerInteract : MonoBehaviour
{
// Start is called before the first frame update
void Start(){
}
// Update is called once per frame
void Update(){
if (Input.GetKeyDown(KeyCode.E))
{
float interactRange = 2f;
Collider[] colliderArray = Physics.OverlapSphere(transform.position, interactRange);
foreach (Collider collider in colliderArray)
{
if (collider.TryGetComponent(out NPCInteractable npcInteractable))
{
npcInteractable.Interact();
}
}
}
}
}
and i was wondering, how to implement a functionality, where a dialogue window disappears after the player walks away from the NPC. can smb help me out? thx
I have a camera in the character that’s attached to the character’s head. The animation causes character to start shaking. I decided to use the Virtual Camera (it follows the empty "zxc" object in the character’s head model) from Cinemachine.When I run the game alone, everything works fine.But when I enter the game with 2 clients,then the script CinemachineVirtualCamera disappears in VirtualCamera and creates a child element cm.
Cache which NPC the player is currently interacting with. Then in Update, if it's not null, check the distance between the two and if it's greater than the interactRange. If so, kill the dialogue.
but im not caching the NPC when im starting the dialogue. so it means that i dont need to do it for ending the dialogue
Okay, if you say so
thanks for your help, had to scrap this idea though lol
Cache the NPCInteractables and release/deactivate them if you exceed a certain distance outside of the input if-statement.
how can I make the enemy have randomized moveemnt and etc.? i currently just have
transform.position = Vector2.MoveTowards(transform.position, playerPrefab.transform.position, moveSpeed * Time.deltaTime);
and I was wondering how to add something like it randomly dashing towards you and etc?
again, i dont understand why i need to cache smth. i asked one person, and all he/she was able to do is to just reacto to my question. so idk if i need to use cache
How would you know which dialogue windows were opened?
You'd cache them... and release them when necessary.
Random targets or variable speed?
how would you know which dialogue is currently playing
without caching it?
do you know what cache means?
yes
doesn't look like it
tf is ur problem?
Caching can mean many things. Which caching do you think people are talking about?
cache memory
Elaborate. What do you think all these people are asking you to do
for some reason they want me to store the dialogue in the cache memory. idk whats the point of it
Please ask in #💻┃unity-talk and not here
Ok perfect 👍 Thanks
Incorrect. They want you to store it in a variable outside of the function so that you can keep the reference across multiple frames
hey i got a problem with saving data https://hastebin.com/share/quyojehihu.csharp
i posted each of my 3 scripts there and error at the end
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Caching is the programming term for "storing something for easier access later" and applies to a lot more than just the memory cache
I have a camera in the character that’s attached to the character’s head. The animation causes character to start shaking. I decided to use the Virtual Camera (it follows the empty "zxc" object in the character’s head model) from Cinemachine.When I run the game alone, everything works fine.But when I enter the game with 2 clients,then the script CinemachineVirtualCamera disappears in VirtualCamera and creates a child element cm. what can i do?
Is the best way to restrict character movement completely enabling and disabling the script?
still doesnt answer my question. its like everyones saying trust me bro idk why but trust me ok ha ha ha. why cant i do smth like this?
sorry, didnt understand
You absolutely can. You just need to reference the NPC. Which you can do by caching the reference when you start interacting with it. Which is what everyone is telling you to do
Nobody is saying "idk why" they were very clear about the why
I want to take the controls from player at specific points lets say. Do i completely disable the script that is responsible for movement or is there any other way?
Ideally, you'll separate input from the actual movement logic.
I do that with a "brain" system. I have a PlayerBrain that uses player input to send commands, and I have an AIBrain that makes up its own commands.
Don't be such a baby. I'm sure everyone here would be willing to dive deeper into explaining the concept had your immediate reaction to the multiple answers not been so resistant.
So I could take control from the player by turning off the player brain and turning on another brain
I'd still be using the same movement logic.
Ah okay
If you're talking to an NPC, you need to keep track (cache) what NPC you're talking to. There's nothing more to it than that. When you're out of that NPC's range, tell it to stop talking. When your want it to be your ConversationManager that does so, or the player's Interact script is entirely up to you. Both will work.
This also makes it easy to re-use logic for both players and NPCs
I originally had completely distinct movement logic for players and non-players (a CharacterController vs. a NavMeshAgent) and it was a mess
I still have a NavMeshAgent, but it's used to figure out where to go; it does not actually move the character
Ah okay I see. Thanks
and uh I believe its not recommended for beginners to use the ready assets right? For movement lets say. I dont understand most of the stuff. Which actually made me realize I dont know how the input script and the actual movement script links.
okay. fair enough. but why i dont need to have a ref to the npc, when im starting the convo? but suddenly i need to have a ref when i want to end it?
You have a reference when you start the conversation. You just don't store it anywhere since that triggering event is done you no longer have a reference to it
Basically, right now you are asking "Why would I need your phone number, you're right in front of me?"
The reference is so you can contact it later, when it's no longer directly involved in the collision or whatever starts your dialogue
How to remove camera shake due to character animation? The camera is located in the character's head model
animation channel bro 😢
i checked online but the options they have and i have are different
read my messages starting from here
make camera follow a smarter target
game logic should never be tied to graphics
if your camera targets the head, and head is moved by animation, then animation now changes your camera, which is wrong
camera should target a different object, probably the actual physics shape.
blue capsule collider, for red character animation. Camera should target a position based on the blue capsule collider
okay. i was thinking about doing smth like this. and later just using the var npc. am i on the right track?
@polar wasp i used the buoyancy u suggested
i think it looks alright
just gotta increase the force a tiny bit so that the camera doesnt go below the water surface
Configure your !ide before receiving help
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
@swift crag @polar acorn thanks for yalls help yesterday, learned more about canvas and event system. problem ended up being a player cam locked the cursor
Doing a secondary overlapsphere with a smaller radius vs calculating the previous overlap operation and comparing distances with each collider?
that kind of depends on how much crap is near/on the sphere
and they are all relevant?
yes, basically I've difference ranges for what I need to compare against
Note; My knowledge is primarily for 2D.
Collider2D.Distance is generally faster. Imagine how fast you can cache and do all sorts of gymnastics to calculate the distance. Collider2D.Distance is slightly faster than that, but less headache.
and .Distance is substantially faster than any Physics query
in my own depenetration for my physics engine, I call OverlapCollider, get a giant list, create structs with results of .Distance, then I sort and work with that.
Ah, ok sounds reasonable enough, but getting to the point where my targeting script is becoming the bulk of my operations
ive so much to benchmark already x_x
i do some crude benchmarking by turning off my camera and cranking up the timescale
just call OverlapSphere 10k times, and .Distance 10k times. That’s all you need
it simulates running the game at 10 FPS in real-time (so if it can do 100 FPS, i run it at 10x speed)
pretty handy for quickly spotting problems
as well as for looking for weird edge cases
you are asking a question that can only be answered by benchmarking.
and you should have your own benchmarking helper functions to help you do this faster
if you can wait, I have something like this, and I can send you my benchmark (for 2D) to you over lunch
Ah, appreciate it, but mostly dealing with 3D and 3D physic queries atm
i mean i send code, and you change it to the corresponding 3D queries to test
oh, sure ill take a look at it. Throw it up on a repo and ill take a look
no rush, I'm debugging a lot of other things ;p
if you have a massive number of enemies (like a bullet hell), you might need a non-physics solution
it might need a data-based solution
where you store shit in a data structure, do your own updates, do your own rendering, etc
eg vampire survivors
there's probably a lot I can cut down on using jobs, but I am offloading a lot to the GPU
as rendering right now is pretty cheap (mostly primitives or sprites)
you can also go the game design route, to restrict what you can spam
mario maker can only handle 200 goombas at once.
well, it can handle a lot more, but you are limitted to 100, then with an extra limit to actually allow 200
point being, you can restrict the number of goombas
honestly, rendering and stuff like pathfinding ive gotten pretty cheap
it's just the collisional and targeting stuff that eats away at my frames
hitting 1000+ enemies with a fireball in a single frame usually a big oof
you can also make the targetting dumber
I'm trying to give my player XP upon killing an enemy, but it doesn't work, is it something to do with prefabs?
https://hastebin.skyra.pw/tuxeniciku.csharp
that's not the same component as the script
does OnTriggerEnter function necessarily needs to be in the script attached to the trigger GameObject ?
I'd like to have the script attached to an other game object (not the trigger), but call OnTriggerEnter in that script for an other GameObject set as trigger.
yeah you asigned player script instead of player xp manager i think?
but I can't drag the PlayerXPManager script on? all I can do is drag the player prefab
OnTriggerEnter is called on that specific gameobject when that specific gameobject enters into an area of another's compatible collider
both need a colliders, one needs IsTrigger, and one needs a rigidbody (can be kinematic)
we not talking about it
Ok so it needs to be attached to the Trigger GameObject itself, even if the said trigger is a child object of the one with the script ?
so what am I supposed to put there? I can't drag anything except the player
Correct. And that is expected
You want the object WITH the script, not the script itself of course
not sure of the exact context, but if you want to send the callback of the trigger to another gameobject, like say if the child should notify the parent gameobject when it recieves a trigger callback, then you'd simply send the parent reference to the child (or event) to notify the parent object scripts
yeah so shouldn't everything be good in the inspector? am I supposed to use GetComponent instead?
ok that's precisely what I will do then. Just thought it would be better for organization to have all script on parent but this will work thanks 👍 🙂
usually I keep my parents as the managers, but for the more active in scene stuff would be child to that container
I dunno the context to this conversation, so I dunno
Is that a prefab image you are showing. And is player a scene object?
I have a SimpleEnemy prefab with a SimpleEnemy.cs script, it derives from Enemy.cs (https://hastebin.skyra.pw/tuxeniciku.csharp), I want to add the "worthXP" to "currentXP", but killing an enemy doesn't add any xp (currently set to 21.5"
im extremely bad at explaining sorry
i feel like this has something to do with prefabs though, idk if im correct tho
your enemy should simply not have a direct reference to the PlayerXPManager
That code is not a simpleenemy script
It is enemy
So that component is something different
I see mao said that a while ago
you can also try to get this xp manager by
PlayerXPManager playerXPManager = FindObjectOfType<PlayerXPManager>();
oh yeah that works
I didn't know how to properly get the currentXP value, so i did that
cool
@summer stump i see you reacted to evevemue's msg, is that not the corrcet way to do it? it works, but is there a more simple way or?
You never want to use find
sure its not the best way
A singleton would be better for manager types, but in this case what praetor said is inportant
FindObjectOfType<T> is fine to use, sparingly
Find is the one you should never use. FindObjectOfType is one you should try not to use
Agreed, but specifically here I think it is a really bad choice
The only times you should use it are when there is exactly one instance in the scene so you know what you're getting, which is also the conditions under which that object is a good candidate for a Singleton
okay, thank you all
Id more likely to abuse statics and singletons before I ever touch Find. No reason not to know where the things I instantiate are at.
the scene itself is just a large container
dude that looks great
any time
are you thinking of making a deceleration variable for it?
yeah
hardest bit is gonna be the animation of the parachute deploying
and the model
bro.. u doing a battle-royale?
why did no one tell me linear algebra was so hard
I just let Unity do it (:
I don't understand the use-case of having an Audiomanager play clips versus just playing audioclips at a source. It doesn't seem like AudioManagers have any managing methods that make them worth it to use. Can someone please explain to me when it would be best to use an Audiomanager?
well, you'd have to write some "managing methods" to get any use out of it (:
Notably, an "audio manager" could rate-limit sound effects
by only allowing three of a certain kind of sound to be played at once, for example
so u dont need dozens of audiosources?
It could also be responsible for controlling the volume of the one-shot sounds
so that individual sound makers don't have to go look up the current volume setting
It doesn't seem like AudioManagers have any managing methods that make them worth it to use.
I don't underatand this
You would of course MAKE those methods yourself
I can use this method to use only a single audio source.
public void Play2DClipAtPoint(AudioClip clip, float pitch)
{
// Create a temporary audio source object
GameObject tempAudioSource = new GameObject("TempAudio");
tempAudioSource.transform.position = Camera.main.transform.position;
// Add an audio source
AudioSource audioSource = tempAudioSource.AddComponent<AudioSource>();
// Add the clip to the audio source
audioSource.clip = clip;
audioSource.pitch = pitch;
// Set the volume
//audioSource.volume = this.sfxVolume;
// Set properties so it's 2D sound
audioSource.spatialBlend = 0.0f;
// Play the audio
audioSource.Play();
// Set it to self destroy
Destroy(tempAudioSource, clip.length);
}
thats basically an audiomanager..
i misunderstood what u meant..
i thought u meant having ur clips already loaded up in ur sources.. and just calling sources for w/e thing u want
but see here ur already managing an audiosource.. (setting a clip, modifying params, then playing it)
I didn't know this method was comparable to an AudioManager, so just trying to see if there's any reason for me to use that class if I have this method.
an audiomanager would just be a robust version of something like this.. (i personally keep around a few audiosources (as children of the manager) 1 for gfx, 1 for music, 1 for player sounds..
AudioManager is something YOU make.
i pass in the clip thru the function and it just plays it..
ya, @austere hedge , its not a built in component or anything..
its just a script u wrote that manages audio/audiosources
I understand now. Thanks guys.
Single principle part of SOLID
its sole purpose is to handle audio
nothing more nothing less
heres mine.. pretty newbie version.. but thats all it does
although.. seems like somethign that could very well be a built-in component some-day
i'd use it lol
How do I change a bool variable upon finishing an animation of a GameObject ? (variable would be in script attached to object)
could use an animation event to call a function that flips it off for ya
would just put it on the last keyframe
hey guys. i have this piece of code and i want to check the distance between the player and the NPC. can smb help me out with this? thx
public class PlayerInteract : MonoBehaviour
{
// Start is called before the first frame update
void Start(){
}
// Update is called once per frame
void Update(){
float interactRange = 2f;
Collider[] colliderArray = Physics.OverlapSphere(transform.position, interactRange);
if (Input.GetKeyDown(KeyCode.E))
{
NPCInteractable npc = new NPCInteractable();
foreach (Collider collider in colliderArray)
{
if (collider.TryGetComponent(out npc))
{
npc.Interact();
}
}
}
if(distance between the NPC and player > interactRange)
{
npc.EndConversation();
}
}
}
https://docs.unity3d.com/ScriptReference/Vector3.Distance.html
this is your friend here
theres no explanation there haha
it's not Vector3.GetDistanceBetweenNPCAndPlayer
it's Vector3.Distance
It's even formulated nearly the same
the page explains what the Vector3.Distance method does
I'm not sure what kind of explanation beyond that you were expecting.
well, since the method accepts arguments/params, it'd be nice if the 'documentation' would explain what args/params the method is expecting. bc rn i cant read people's minds and know what the f is other
Read for God's sake
The example code is showing how to measure the distance to another Transform.
...which is the other transform
But that's totally irrelevant, because you don't need to see the example code to know what Vector3.Distance does
You don't need to write an entire class that has a public field called other to use Vector3.Distance
That code is an example of how to use Vector3.Distance
other is not a an argument to Vector3.Distance. It is part of the example code.
You seem incredibly confused about the concept of an example...
Sometimes I feel like there should be a level below beginner
Basic logic and reading skills are kind of necessary
yeah, should make a #code-for-me
This is a joke, right?
Stop ?-reacting everything and start giving this an ounce of critical thought.
This is ridiculous.
is playerprefs the easiest method to store data?
It requires the least effort to start using, yes.
Easiest and least practical (for larger amounts of data)
It's fine for small amounts of data.
Sorry if my message was confusing. The page clearly describes the parameters you need to use, you don't need to read minds. So I assumed you were making a joke with your comment
I truly hope it was a joke...
But it's not appropriate for large amounts of structured data.
okay, i dont need a lot of data and also dont need to secure them for now
Use it if all you need to do is write "player level is 10 and player money is 3000"
it's easiest, but it stores the data in the OS registry. and that tilts me to no end, they should really consider removing the whole class
it should really just go to a file in the persistent data path or something
KSP2 had a great bug where it'd write huge amounts of data to PlayerPrefs (it was a malfunctioning editor tool that also wound up in the build, iirc)
If you want to store a list of items the player has, and every single skill they've unlocked, you'll be much better served by using Json.NET to serialize and deserialize a whole "save data" class
so far i have this, but i dont understand what to write as a first argument for the Distance method? whose Vector to use? what to use instead of the question mark?
float distance = Vector3.distance(???,transform.position);
What else needs to be explained? You give it two vectors. It tells you the distance between them
What do you want to get the distance between? This object and what?
i dont know. i just got told to use this method. but i would like to measure the distance between the npc and the player
If you want to get the distance between the NPC and the player, and the function gets the distance between two points, it would stand to reason you should pass in the positions of the NPC and the Player
Just to repeat what I said on the other server
Assuming transform.position is the player, then you plug in the npc.transform.position, right?
And hariedos apt response
"What's the distance between point A and point B? Distance(???,B)"
but the NPC doesnt have a vector
How?
How is that possible
That makes no sense
Is the NPC not a gameobject?
All gameobjects have a position
Does it exist
As I said before:
npc.transform.position
I dunno your code, so of course replace npc with your reference
Right?
You have the npc, so get its transform, and from there get its position
idk how and why. its some strange $hiet. look, my NPC class looks like this:
public class NPCInteractable : MonoBehaviour
{
[SerializeField] private NPCConversation npcConversation;
public void Interact()
{
ConversationManager.Instance.StartConversation(npcConversation);
}
public void EndConversation()
{
ConversationManager.Instance.EndConversation();
}
}
it obv inherits MonoBehavior. Idk what methods and fields it has. But if i serach the 'documentation' for vector, it doesnt have any results:
So it does, in fact, exist. That means it has a position
So get the position of it
but transform.position gives you the player's position, or no?
Why would you search for vector?
Just write what I told you...
Yes. Because you're calling it on this object.
Whats wrong here? im confused
Which is why I said NPC.transform.position
If you want the NPCs position, call it on the NPCs transform
ummm? bc i need to give it for the Distance method? 😄
nvm i see now
Yes, but searching vector on that page makes no sense.
It is in the transform.
nvm i dont
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Christ on a cracker man vector is a type. Many things return vectors. Like position which you are already using
You need to go back to the extreme basics @sour yew
This is crazy
Understanding dot notation is a requirement to code
What is the error message?
Always start with the error.
Assets\Scripts\DataGroup.cs(11,35): error CS0236: A field initializer cannot reference the non-static field, method, or property 'DataGroup.valueablePieces'
Just please do a little bit of logical processing. Apply knowledge from scenario A to scenario B
You cannot use the value of a non static field outside of a function. Set the value in start or so e other function
okay thanks
This one is a bit jargon-y, yeah
so im having a problem (and please tell me if this is an of-topic question) with vscode. when im coding i dont get any "suggestions" or "Intellisense". ive tried a bunch of things like re-choosing the external editor and instaling a bunch of extentions to vscode and even chat gpt isnt any help to fixing the problem. please tell me if there is a solution please (thanks in advance)
You can't initialize a field with another (non-static) field, basically
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
public class Whatever {
public static int staticVariable = 123;
public int foo = staticVariable;
public int bar = baz;
public int baz = bar;
}
foo is fine because it uses a static variable. bar and baz are not
Show external tools menu
thank you
And it should be kinda clear why this isn't allowed -- how would you even resolve that?
ok wait a min
The compiler doesn't want to have to figure out an order that it makes sense to initialize the fields in, so it just says no
can you also let me know if this is a good way to store data? first i gather all data i want to save in data script
public BuyButtonManager buyButtonManager;
public MoneyManager moneyManager;
public int piecesValueMulti;
public float priceVal;
public float spawnSpeed;
public float priceChessboard;
public int money;
private void Start()
{
piecesValueMulti = valueablePieces.piecesValueMulti;
priceVal = valueablePieces.priceVal;
spawnSpeed = buyButtonManager.spawnSpeed;
priceChessboard = buyButtonManager.priceChessboard;
money = moneyManager.money;
}
and then just gonna use PlayerPrefs in another script to save and set them all
I wouldn't copy the variables into this class.
I would just directly get the values when I'm saving
(and directly set the values when loading)
how is dot notation related to this? 😄
but is it gonna work?
well, it's going to copy the values out of those three components when Start runs
so if valueablePieces.piecesValueMulti changes between when Start() is called and when you save your own piecesValueMulti field, you'll have a stale value
im sorry i cant show you for some reason the print screen or win + shift + s are bowth not working for some reason
Because you don't seem to know that you can access the transform of another variable
and what if i change script execution order?
Which is what the dot operator does
That wouldn't change the fact that you write these value down when the game starts and then never change them again
Oof. It's how you access the npc's position. It is the crux of your misunderstanding. 
Huh ok. Um. If you open snip and sketch manually, does that work?
i can use my phone acualy
Pretty sure the crux of their misunderstanding is an inability to synthesize information and apply the same concepts in novel situations. A fundamental lack of critical thinking
Fair
i remember having this happen before. i also forget how i fixed it.
i'd just restart the machine and see if it clears up
indeed.
you have to be able to join the dots here...
- every monobehaviour has a transform
- every transform has a position
- i have a monobehaviour that represents the NPC
- i can calculate the distance between two positions
If you refuse to do this, you will fail miserably.
And it literally is just joining the dots 😭
ffs. ive been told that transform.position give you players position. and now suddenly, if i apply the same thing for an npc, now i magically can get npc's position :DDDD. so if i have this:
Dog dog=new Dog();
dog.name;//gives me dog's name
but then if i follow ur logic, i can do this:
Dog dog=new Dog();
dog.name;//gives me dog's name
Cat cat=new Cat();
cat.dog.name;
this doesnt make any sense, and you keep telling me that it does 😄 😄 😄
perhaps you are unclear on the meaning of transform
Here it comes(if you are wondering why 3 pics it is because I have a bunch of other extensions for other languages)
What
in C#, if you don't qualify a name, it's implicitly accessing something on this
this is a reference to your own object
transform.position gives you the position of the object you call it in.
npc.transform.position gives you the position of the object you call npc
Just because you are refusing to think doesn't make that not true
Please, try to think
it is an object, and position is a field
transform.position
in reality, this is
this.transform.position
this.transform.position is the player's position because this is an object attached to the player's game object
Literally what. Why do you think this. No one is saying anything remotely the similar to this why is this your takeaway
someoneElse.transform.position is someone else's position because someoneElse is a reference to a component atached to their game object
I wanted the external tools menu
ffs. finally someone knows some stuff. thanks!
I must point out that I've managed to help you despite your best efforts here.
This is not what anyone is saying btw. This is a failure to think on your part
Correct your attitude or you won't be getting any help here.
This is fundamentally how c# works. This is something you should absolutely 1000% already know before doing anything further and you've been told this
They said the same thing I was saying
You have absolutely no clue what is going on and it is embarrassing
And this happens every time you ask for help
Next time please understand that you know NOTHING, and we are trying to help, so just work with us instead of against us like some 12 year old kid that thinks they know everything
oooooh i understant wait a litle
Literally everyone was saying this. You were just too thick to actually put two and two together
Is this what you meant?
Yes.
Check the first two checkboxes there and click regenerate project files
ok ill try that
Putting on record now, but if this is the kind of attitude you're going to give here, you're not going to be allowed post. Consider this a warning.
um i relised i hadnt downloaded .net v6 so i did and now i have this error: 2024-03-19 18:17:11.727 [info] The .NET SDK installed on the machine is targeting a different platform (win10-x86) with the C# Dev Kit (visualstudio-projectsystem-buildhost.win32-x64), and are incompatible. 2024-03-19 18:17:11.730 [info] Project system initialization finished. 0 project(s) are loaded, and 1 failed to load.
plus i did what you said and it didnt work😕
regeen project files
Yeah, won't work with the sdk issue
Ok yeah, that's what I was thinking
@queen adder
What is confusing you about what osteel said?
usually "The .NET SDK installed " says too me its installed but project .csproj files might be associated with another thing
when?
#💻┃code-beginner message
What do you mean when?
You ?-reacted here
I created a StateMachine behavior script in the animator of my GameObject.
How can I change a bool parameter when the animation ends ? The animation keeps looping and the function is never called.....
if the state doesn't exit, OnStateExit won't run
cause i dont get it
thought they were talking to bradyaga
how do I know if the state exists ? The script is attached to an animation state btw
wdym if it exists? It exists if it's in your animator state machine.
Bradyaga has a long history of being aggressive and not listening to people, so they got warned
Why do you even need to get it, it wasn't directed to you
What's the question?
Did you mean to say exits? You said "exists"
the state exits when the animator moves to a different state
it does that through transitions
i just reacted a question mark dude and u be asking me stuff now?
uncheck loop on victory animation clip
if you mean the state, put like a animation event
Because it was weird. Questioning the mods about stuff you have nothing to do with is a super weird thing to do
But yeah, I'm out. Bye
ok I did that I'll see if that works
Under what condition should it stop looping?
You are prob still stuck in state if bool stays true,
then I'd use animation event to set it back or switch to trigger
I got it to work, had to uncheck loop + having no condition for exit transition + having an exit time
thanks for helping ^-^
ok dude
Hey, I'm adding a value to an object's position to set it, but that doesn't work well when changing resolutions. I suppose I should multiply by some value but I don't know what it is. Any idea?
Don't know if that's clear
probably Screen.Width/Height ?
Maybe show what you've tried so far
why is the spread so buggy??
I doubt that would work since the ratio is always 16/9
because euler angles == sad
how should i do that then
My guess would have been 1920/Screen.height but it's not that I checked already
share your code in a way I can copy paste
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
cos I set it at 1920*1080
also why base it off highlight.rotation instead of just using the mouse position/direction?
Are you referring to the implicit dead zones or the combination of vertical and horizontal projectiles during a single shot (in some instances)?
if (Input.GetButtonUp("Fire1"))
{
if (highlight != null)
{
int shellCount = 14;
float spread = 1;
Quaternion offSet = Quaternion.Euler(0, 0, 90);
Quaternion newRot = highlight.transform.rotation ;
for (int i = 0; i < shellCount; i++)
{
float addOffset = (i - (shellCount / 2)) * spread;
newRot = Quaternion.Euler(0,0, highlight.transform.eulerAngles.z + addOffset + 90);
Shell = Instantiate(Bullet, highlight.transform.position, newRot);
}
}
Destroy(highlight);
}
the vertical/horizontal thingy
found it easier and faster to do
Something like this:
if (Input.GetButtonUp("Fire1"))
{
if (highlight != null)
{
int shellCount = 14;
float angleOfSpread = 20; // 20 degrees for the whole cone. Set to whatever oyu want
float degreesPerShell = shellCount / angleOfSpread;
Quaternion offset = Quaternion.Euler(0, 0, 90); // correcting for up vs right I guess?
Quaternion startRot = highlight.transform.rotation * Quaternion.Euler(0, 0, -angleOfSpread / 2f);
for (int i = 0; i < shellCount; i++)
{
Quaternion shellRotation = startRot * offset * Quaternion.Euler(0, 0, degreesPerShell * i);
Shell = Instantiate(Bullet, highlight.transform.position, shellRotation);
}
}
Destroy(highlight);
}```
Not entirely sure but we may need to know how you're moving the projectiles as well.
it's just some rigid body velocity
still happening
I'm assuming their placements isn't the issue but that the orientation has something to do with the direction they travel
you'd need to show your other code then
the bullet one?
probably a bug in how you're setting the highlight up or how you're firing.moving the projectiles
that but more like the rest of the code in this class too
or all of the code?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CombatSystem : MonoBehaviour
{
[SerializeField] private GameObject AOE;
[SerializeField] private GameObject Bullet;
private GameObject highlight;
private GameObject Shell;
void Update()
{
if (Input.GetButton("Fire1"))
{
if (Input.GetButtonDown("Fire1"))
{
highlight = Instantiate(AOE);
}
if (highlight != null)
{
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 Dir = (mousePos - (Vector2)transform.position).normalized;
highlight.transform.up = Dir;
highlight.transform.position = transform.position;
}
}
if (Input.GetButtonUp("Fire1"))
{
if (highlight != null)
{
int shellCount = 14;
float angleOfSpread = 20; // 20 degrees for the whole cone. Set to whatever oyu want
float degreesPerShell = shellCount / angleOfSpread;
Quaternion offset = Quaternion.Euler(0, 0, 90);
Quaternion startRot = highlight.transform.rotation * Quaternion.Euler(0, 0, -angleOfSpread / 2f);
for (int i = 0; i < shellCount; i++)
{
Quaternion shellRotation = startRot * offset * Quaternion.Euler(0, 0, degreesPerShell * i);
Shell = Instantiate(Bullet, highlight.transform.position, shellRotation);
}
}
Destroy(highlight);
}
}
}
this is the whole class
yeah show the bullet code too
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletScript : MonoBehaviour
{
public float speed = 20f;
public Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
rb.velocity = transform.right * speed;
}
void OnTriggerEnter2D(Collider2D hitInfo)
{
Destroy(gameObject);
}
}
show the inspector for the bullets?
and the player
you cut the inspector off here
this is everything except the inspector
oh yea mb
I'm assuming multiple access of the z component of euler angles has returned different results. Perhaps cache it prior to the for loop and use the fixed value.
your bullets are problaby just colliding with the player square TBH
i'll try to disable the player collision
lmao u were right
Hello, I have a question, I have a timer that starts at the beginning of the game and i want it to stop when my character hits that cubic hitbox
I'd like to know what I have to put inside the OnTriggerEnter
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
the opposite of Start.
Although if you are doing multiplayer and do not even know how to format a OnTriggerEnter method correctly you are in for a world of pain
Im really not familiar with all those methods
https://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html
- when something collides with trigger check if its the player..
- can do this by checking for certain components (or even a tag) such as
if(other.ComareTag("PlayersTag")) - do the logic..
{ timeIsRunning = false; }
you need to be before even thinking about multi player
do you need code for text not to be affected by post processing
Have you googled any methods to remove objects from post processing?
i have and could only find 3d tuts and a 2d one using code
maybe im just bad at googling
Hey I'm making a racing game for unity in school and I am not able to do a scoreboard at all
i have this instance of a script and i wanna call a method whenever the player respawns. problem is that whenever the player respawns it tells me that the instance is null. what might the problem be?
I tried to make a timer but it isn't starting after I load the main Game screen
Havent done 2d myself but I imagined the methods would be the same, since you're still just using unity
look up a tutoria in youtube s
what is switchGravityInstance and where do you assign to it
if you need an online scoreboard i used a tut on yt that was like 3 min and it worked
is there someone just starting out trying to create something, as i am just starting out and have no idea on what to create so ill just help in your project
yh i have just watched it i think it could work on 2d
this is in the same script as the inital screenshot
!collab 👇
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
no only scoreboard
just local
show the full code
thanks
I looked alot of tutorials and still the timer isn't starting
A tool for sharing your source code with the world!
dont mind the comments
that one method is the only place you seem to use that object. are you certain that the GameObject with the PlayerLife component also has a SwitchGravity component attached?
the PlayerLife script is on the player but the player does not have the SwitchGravity script attached
well that's why
but the script wouldnt make sense if it was on the player
then why are you checking the player's GameObject for that component?
oops
thank you
I tried it by making the button to start the race switching the bool to true
but still no feedback, not even in the console
the script is assigned to a gameobject
right click isRacing > find all references
look at everything that modifies it and if there are any errors
what if I want to reuse a component in an enemy but methods require this "context"?
pass it down?
but enemies dont have inputs
pass null, handle it, or
separate the input from the behavior
wrap methods like that into an input receiver and the method that actually does something
Correct answer.
oh so I should make another method that calls this method?
struggling to make my camera not inverted :/ can someone help?
which doesnt need the context
void OnShootInput(context) => Shoot();
You should make a class that handles Input, which then calls stuff on your Player component.
- get your !IDE configured
- don't multiply mouse input by deltaTime, mouse input is already frame rate independent
- obligatory "use cinemachine"
- - instead of + if you want to reverse the current controls
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Now what your player can do is separated from input.
Or yeah just make an overload, a method which has the same name, but no parameters. This is allowed in C#
yeah, I do have an InputManager
And one calls the other
but events need context right?
ooooooh I see
I should create methods in the InputScript that call the Shoot Method in other script, right?
yes
thanks a lot
Think of the player like a puppet. Your Input is just the one pulling the strings.
Theoretically, you can have anything "pulling the strings".
Whether that be input from the player, or some AI.
I notice that you have a Coroutine there. Keep in mind that the player should still handle the management of its state. Your Input script can keep hammering the Shoot method every time the user presses a button. The player should just know that it's already shooting, and shouldn't do so again until ready.
Thank you! but iim a big time newb and im not sure how thatd look in code. I was able to fix the up and down but now my horizontal is inverted lmao
have you gotten your IDE configured yet?
idk what that means 🫤
yo
how do I have an UI pop up when I am close to an object
like an interaction ui
have you tried typing that exact question into google ?
oh.. always best to check there first, you'd be surpised how many people wanting to do this for years
Use a trigger collider
yeah found an reddit post with description on kinda what to do
so imma take that to ai
jezus dont please
--
yeah I really do want to learn
You could instead try reading it, look up things you don't know, and understand what it says
but rn I have around 9 days to complete an game alone with slim very slim experience with coding
lets face it calling it AI is a bit of an overstatement..
its a fancy search engine..nothing "intelligent" about it
Next we'll see "why doesnt this work"
//use this function to detect when close to an object
void OnTriggerEnter(...)
{
// make the object you want visible
}
so I am really tight with time
but I will deff learn coding after these days when I have time
Sorry if i'm interrupting. I've got i simple question why don't i get proper typehints?
cuz rn I just need to complete it
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
9 days for a game from scratch? No, you had a few months and panicked when you realized the assignment is due very soon
I had maybe 2 months
and u waited until a week and a half?
bro it is complicated
Yup, it may be way too late now
2 months is enough time to make a smal game
It is
ive done a whole map and a lot of models in just some days
no prior experience or knowledge of how to make a game? 9 days is way too low
It says nothing about wrong/missing typehinting
I (someone who has been coding for 10 years) couldnt even be paid to make a game in 9 days.
games take time
doing assets compared to the code is a cake walk
Well, with nine days you'd better hit the books and start a deep dive of the documentation
Learn the basics, do a simple game, get an average grade and let this be a lesson for the next one
yeah I know
If your IDE is not autocompleting code
it's right there
I'm making a horror game alr
with task thingy
and I have an interaction and walk system
but I need more comlicated
Okay i finally got it, thanks you 🙂
and ofc make it a little better for the end prod
watch a youtube tutorial..
yeah I have found some that has been helpful
😉 meaning you just need to do the other 99% of the actual game
great! if your IDE is finally configured, then you can now actually get help here.
copying and pasting EXACTLY and using pre-made assets from the unity store is probably ur only solution considering the circumnstances
Literally the first line
can you find scripts n stuff in asset store?
like actual game making scripts
and not just mov
Yes but you'll have to pay and often these are not cheap or worth it.
There was an AI system that went on sale, got it as part of a bundle and it was absolutely unusable
yeah rn I'm using perplexity
yap, AI is whats gonna screw you over
good coding ai
I have a method called PlaySound.
public static void PlaySound(Sound sound, float volume, float pitch)
"Sound" is an enum. From a different class, I'm trying to call that method.
SfxController.PlaySound(Sound.AttackFlesh1, 1f, 1f);
Sound.AttackFlesh1-4 works. But I have 4 different AttackFlesh sound effects, so what I want to do is this:
int i = Random.Range(1, 5);
SfxController.PlaySound(Sound.AttackFlesh[i], 1f, 1f);
However, I get an error. Does anyone know what I'm missing?
or ai in gen