#💻┃code-beginner
1 messages · Page 98 of 1
what is static for?
it needs to be public to be accessible by other objects. static makes it not tied to an instance and is owned by the class instead
from what I understand its for variables that are read only
that is also incorrect
ah gotcha, i don't need it to be public but rather just be accessible by other scripts
i see
from what I've been told you're meant to make things private as often as you can
just for the sake of good security or something
not security, encapsulation
If that's the case, then why are you accessing it from the instance instead of the class?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class FPSController : MonoBehaviour
{
public float sensX;
public float sensY;
public Controls controls;
private InputAction OnFoot;
public Transform orientation;
float xRotation;
float yRotation;
// Start is called before the first frame update
void onEnable(){
OnFoot.Enable();
}
void onDisable(){
OnFoot.Disable();
}
void Start()
{
controls = new Controls();
OnFoot = controls.ActionMap.Camera;
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
// Update is called once per frame
void Update()
{
Debug.Log(OnFoot.ReadValue<Vector2>());
float mouseX = OnFoot.ReadValue<Vector2>().x * sensX;
float mouseY = OnFoot.ReadValue<Vector2>().y * sensY;
yRotation += mouseX;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.rotation = Quaternion.Euler(xRotation,yRotation,0);
orientation.rotation = Quaternion.Euler(0,yRotation,0);
}
}
when i move my mouse, the console reads the mouse's position and returns 0,0 all the time. Why?
a little background info:
I am working on a fps esque camera system and yes, ive tried turning off Cursor.lockState = CursorLockMode.Locked; and Cursor.visible = false;.
long story short i want to instantiate objects from a central script instead of jumping around
something that is private is only accessible by the type it is declared it. if you want it to be accessible by other types then it needs to be public.
oh this is easy
alright, thanks. That makes sense now
where do you call onEnable
You need to change Start to Awake.
You also need to change onEnable to OnEnable
i thought unity handles that 🤦
honestly its like a curse
most of my problems come from the most miniscule and easy to fix bugs
but i can never find the problem
make sure that your !IDE is configured to help you prevent simple spelling mistakes
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
Should I use something other than PlasticSCM? I like PlasticSCM because it doesn't upload my assets downloaded from the Unity store.
then fix it. it is a requirement to receive help here because nobody wants to play septic's Personal Spell Checker
ive looked through almost every page on stack overflow that i could and nothing works for my vscode
ah
ok that
makes sense
sorry
then swtich to visual studio because it is not only better, but easier to configure and less likely to break
will consider
yeah i dont recommend using other IDE's, every time I ask a teacher or someone I know the main takeaway is that visual studio is better in every way
i honestly
in my opinion
prefer arch linux + visual studio code
its SOOO much easier to set up libraries
this way
if it's easier then why is your ide unconfigured 😉
bahh im a messy and lazy person
in this case however seeing that it is a requirement to be here and ask for help, i will try and switch
thank you all
and THANK GOD this FPS look around works now
i'd like to thank my manager
oh i'd also like to recommend using cinemachine instead of coding your camera controls manually. it's typically a lot better
You're playing with fire using vscode. If you can't configure it or understand how to debug errors yourself, I'd consider switching
It often breaks (loses intellisense), and is no longer supported. This is coming from a vscode user, myself . . .
"You're playing with fire using vscode."
for unity? or in general?
unity
Highly recommend Rider
CONSIDERING that C# was made by microsoft
Damn you capitalism!!!
anywho, see you later
is there a way to find an object by name
yes but don't
yes, you can use GameObject.Find, however there are better ways to reference other objects
why 😭
is it bad even if only one of the objects exists
Use a singleton access pattern then
Only for Unity. It's fine to use, just understand the difficulties that lie ahead, or what this guy said . . .
#💻┃code-beginner message
👍
how do i go about this, in this screen shot the enemy can see the player
but in this screenshot he should technically be able to see him
but he doesnt because the blue line goes to the belly of the player
and it isnt in the angles anymore
but the enemy can still clearly see the head
had this problem before, you wanna assign a child empty on the player and have the enemy look for that instead. When you tell it to look for the player's transform, the belly is the center of the transform
you basically just move around the child empty where you would want it to be on the player and that should fix it
but the thing is that later on im gonna have a rig on my player
so each body part will have a collider
so i was thinking of using a raycast somehow
inside the vision area angles
use a spherecast
because i need the enemy to even see a foot
or a boxcast
you might wanna have a separate check entirely when within a small range. Maybe a simple boxcast or overlapSphere or something
i was thinking of that
that's what I did for enemies that would attack you within a certain melee range
should I use rigidbody for collsion or am i supposed to code it myself from scratch?
Colliders are for collisions. What specifically are you asking?
I mean for player movement do I just rely on colliders or do I use raycast
to stop the player from going through walls
Well it depends on how you're moving, which I see is why you brought up rigidbodies.
Using rigidbodies will handle collisions for you for the most part.
If you move with the transform, you're gonna have to query around yourself for collisions, grounding, and anything you want like that
ok thank you
There wouldn't be a physics engine in Unity if you were meant to code it from scratch
colliders cant be used for triggers now and unity separated the two ?
Ok
Physics messages aren't necessarily collisions. I assumed they meant just bumping into things
But yes, a dynamic rigidbody (or CharacterController) is required for OnTriggerEnter
Wait, maybe I misunderstood. What are you saying?
In unity5/2018 I used colliders as reference areas for trigger (like my cars had a collider around the door so the player could open ithe door when near the car) and for aggro ranges on mobs (mobs had a sphere collider preset to it's aggro ranges) and each mob/player carried several colliders as area reference
since I dont want to give the wrong advice I want to know since colliders were brought up if unity changed that since then
Yeah, trigger colliders are still a thing, and that is a normal use for them
Having sight/aggro ranges with colliders is very common still
You can also do spatial queries like OverlapSphere though
I also used them for premade offsets like spells/particle graphics / gfx as well since an arrow would always be shot from a specific side (left/right/top/down) so I just preplaced the sprite and made it invisible. I prefered to do this rather than calculate an offset from the .transform every time
im not sure why i am not able to jump here
start debugging it
where do i put it?
I saw a ping and it disappeared 😦
when are you resetting fJumpPressedRememberTime ?
you only reset fJumpPressedRemember in this code
check inside where u call jump or Grounded state
trhat might be it trying it in unity if i changed fJumpRememberTime to a high value it worked
where should i reset it?
argh it's so difficult to go throught all the beginner training even though I havent done unity for a long time so I just relearn it since so much has probably changed 😦
"How did you feel when the Unity Editor first loaded? In this video, our established creators share how they felt when they opened the Editor for the first time. " - it's like my 100th time 😦 Do I listen to the video or mark as complete 😦
depends on what you want to happen..
I just see what you are always decreasing it, so it just goes down far below 0 and never gets reset
It is to make it so if you just barely arent grounded you can jump
where do you define how long that time should be ?
up top
for some reason vs dosent want me to take scareenshots
here
Just mark as complete. If you don't get anything from it, skip it
You may just want to share the whole script using a paste site
!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.
here
so, do you mean to be decreasing the .2f that you have set there? Because that variable is the one you are decreasing in your code
seems like that would be a value you want to keep constant
how do i fix this?
try thinking through what you are doing instead of just remaining confused, or if you have a specific thing you do not understand, ask a more specific question.. do you expect it to be working right now and you just don't know why?
Im trying to add jump buffering
!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
how can i check why my raycast is false?
like is there a debugger function that lets me see outside the camera
For one thing, pass in the same values to Debug.DrawRay
thanks :DD D DD
Ahhhhh
heres my problem
the layermask may or may not be broken
i'll fix this myself
if FixedUpdate is fixed at 50 frames, how could I make them smoother
Why would you need to
They're designed to be smooth. 50 of them per second, no matter your framerate
what if i want 100
Then change the time step
Hey I am using Unity new Input System, but if I name it public virtual void OnFire() to get different OnFire() in derived class, it wouldn't work
Figured it out, the interacted object was the icosphere, which didn't have the ObjectData script on it. To fix I got the component from the parent of the icosphere
hey guys i want to do something like this effect where the yellow blob will instantly snap to the player if its within certain areas but when its blocked by a collider the blob will just stay within the confines while the cursor moves out, any tips on how to start?
This isnt in unity but im doing a course on responsive web design and its asking me to comment out the line containing the background-color property and value so i can see the effect of only styling the #menu element. What does that mean?
Make a raycast from blob to player:
If raycast hit the player and nothing else then do your things
/* your stuff */```
What wouldn't work?
if i collaborate on github do we need to keep taking turns? can we not all develop at the same time?
you can! just dont recommend working on the same scene together. scripts' merge conflicts can be settled after merging
thanks for the tip!
You don't have to take turns. You can work in parallel.
but then if we push his version will override mine right?
His version of what
like his unity game might look different
If you both work on the same files at the same time you'll need to merge your work
yea but like objects
if somebody builds something
and the other guy like dosent build something
"like objects" is very vague
Projects are made of files
Scene files, assets, script files etc
so every push it will add on rather than "override" the repository??
If you work on the same files you'll have to merge them, that's all
Your view is pretty simplistic. You should do some practice with Git to learn how it works better
All changes will be tracked and it will be up to you how to handle conflicts if any arise
Get axis raw doesnt need to be multiplied by time.delta time correct?
I called OnFire() from new Input System in a State and it wouldn't work
public class WallTextureGenerator : MonoBehaviour
{
[SerializeField] Transform walls, floor;
[SerializeField] Material[] wWallMaterials, bWallMaterials, wFloorMaterials, bFloorMaterials;
void Awake() {
Renderer[] wallTiles = walls.GetComponentsInChildren<Renderer>().Where(c => c.tag == "white" || c.tag == "black").ToArray(),
floorTiles = floor.GetComponentsInChildren<Renderer>().Where(c => c.tag == "white" || c.tag == "black").ToArray();
int wWallMatLength = wWallMaterials.Length,
bWallMatLength = bWallMaterials.Length,
wFloorMatLength = wFloorMaterials.Length,
bFloorMatLength = bFloorMaterials.Length,
wallTilesLength = wallTiles.Length - 1,
floorTilesLength = floorTiles.Length - 1;
for (int i = 0; i < wallTilesLength; i++) {
wallTiles[i].material = wallTiles[i].tag == "white"
? wWallMaterials[Random.Range(0, wWallMatLength)]
: bWallMaterials[Random.Range(0, bWallMatLength)];
}
foreach (Renderer r in floorTiles) {
r.material = r.tag == "white"
? wFloorMaterials[Random.Range(0, wFloorMatLength)]
: bFloorMaterials[Random.Range(0, bFloorMatLength)];
}
}
}
Can anyone tell me why I'm getting an index outside bounds of array error on line 25?
What do you mean by "wouldn't work" and "State"?
Are you getting some kind of error? Something else? Explain.
I am using a StateMachine that controls Player action, however, OnFire() and OnMove() are functions from Unity new Input System and they can only be executed when I put it in a script inside Player (GameObject). However, I want to, for example call OnFire() from a State of the StateMachine. How to do so?
Those are not functions from the input system
Those are your custom functions
yes
how do OnFire() exactly is called
I dont seem to understand this kind of new Input System
here is an example of the code
You'd have to tell me. I can only guess from the limited context here that you're using the PlayerInput component in "Send Messages" mode ? If so, that's how it's called.
how to call those functions from let's say another class inside the PlayerController that I have attached to the player
i don't understand anything about this new Input System so explaining is kinda haard
is using raycast or collisions better for checking if the player is on the ground?
I know a temporary solution which is to add this to the PlayerController
private void OnFire()
{
stateMachine.currentState.OnFire();
}
any better way of doing this
yep that solves the problem for now
still don't know anything about the new Input System
how stupid am I
probably raycast
you dont wanna mess with OnCollisionEnter
casts will be easier and allow you to specify some distance at least. you dont have to raycast, you could capsule cast (in 3d) if you wanted a more accurate version of when any part of the player is grounded
well i have an issue
for some reason scenes are not uploading to github only assets
is that normal do i have to do something to upload the scenes along wth the assedts?
coould it be gitignore??
Scenes ARE assets
It should be very simple for you to check if the scene file is committed or not though. Just look at the changesets. But there's nothing special to do, no
What makes you think they aren't being committed?
https://medal.tv/games/requested/clips/1IMcOSiIs_AS6u/d13375NtWLwm?invite=cr-MSw4eUcsMjAzNDI1NDA5LA
Im having these 2 problems where character can clip through object when moving diagonally, and fly off if moving diagonally at a part of some objects, im using rigidbody for the player
Watch Untitled and millions of other Requested videos on Medal, the largest Game Clip Platform.
well i realized that you need to open the scene
and it dosent just load
You'd have to show your code. Presumably you're not moving your character in a physics aware way
I figured this was your issue
No just Transform
ill send
camera script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Look : MonoBehaviour
{
public Transform player;
public float sensivity = 1f;
private float horizontal;
private float vertical;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Cursor.lockState = CursorLockMode.Locked;
horizontal += sensivity * Input.GetAxisRaw("Mouse X");
vertical += sensivity * Input.GetAxisRaw("Mouse Y");
transform.eulerAngles = new Vector3(-vertical, horizontal, 0);
player.transform.eulerAngles = new Vector3(0, horizontal, 0);
}
}
Player script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public float speed = 1f;
private float verticalInput;
private float horizontalInput;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
verticalInput = Input.GetAxisRaw("Horizontal");
horizontalInput = Input.GetAxisRaw("Vertical");
transform.Translate(Vector3.right * Time.deltaTime * speed * verticalInput);
transform.Translate(Vector3.forward * Time.deltaTime * speed * horizontalInput);
}
}
You have to move your character via Rigidbody velocity or forces if you want proper collisions
Interesting that makes sense ig
ah alr imma try it out, thanks
velocity??
theres a velocity method for rigidbodies!?!?!?
There is a velocity property, yes
!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.
Guys why is my object not going from and to the objects after I put it in the DDOL object?
A property, not a method
What? This is extremely vague, please explain with details what you are asking.
isnt rigidbody.addforce() a method?
i have a question
is there anyway to make something like a library
or a module
uhh basically a script that can be required that returns classes methods etc...
There is asmdefs in Unity to group classes into libraries or you can make a dll project in VS which can be put into a plugins folder in Unity
I cant see the velocity property in inspecter for rigidbodies
https://medal.tv/games/requested/clips/1IMlB5fLmrzxl2/d1337bSKHIhY?invite=cr-MSwzUHosMjAzNDI1NDA5LA
I fixed my problem of the glitching into walls by just putting the code into a void fixed update
Watch Fixed and millions of other Requested videos on Medal, the largest Game Clip Platform.
It's under "info"
whats info?
Only at runtime
u can find it in debug during runtime right?
It's literally called physics.
It has mass, force, energy, you name it.
They might have gotten rid of it here
It's not usual for properties to be shown in the inspector anyway
You can always use Debug.Log or attach a debugger
It might not show up if you are viewing the inspector in debug mode
Guys I need help with my error that says: "InputManager is inaccessible due to its protection level"
I'm using Unity's new Input System package.
The line "using UnityEngine.InputSystem" is fine tho. Line 42 is causing an Error.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.EventSystems;
using TMPro;
using Ink.Runtime;
public class DialugueManager : MonoBehaviour
{
private static DialugueManager instance;
[Header("Dialogue UI")]
[SerializeField] private GameObject dialoguePanel;
[SerializeField] private TextMeshProUGUI dialogueText;
private Story currentStory;
private bool dialogueIsPlaying;
private void Awake()
{
if(instance != null)
{
Debug.LogWarning("Found more than 1 DialugueManager in the scence");
}
instance = this;
}
public static DialugueManager GetInstance()
{
return instance;
}
private void Start()
{
dialogueIsPlaying = false;
dialoguePanel.SetActive(false);
}
private void Update()
{
if(dialogueIsPlaying == false)
{
return;
}
if(InputManager.GetInstance().GetSubmetPressed())
{
}
}
public void EnterDialogueMode(TextAsset inkJSON)
{
currentStory = new Story(inkJSON.text);
dialogueIsPlaying = true;
dialoguePanel.SetActive(true);
ContinueStory();
}
private void ContinueStory()
{
if(currentStory.canContinue)
{
dialogueText.text = currentStory.Continue();
}
else
{
ExitDialogueMode();
}
}
private void ExitDialogueMode()
{
dialogueIsPlaying = false;
dialoguePanel.SetActive(false);
dialogueText.text = "";
}
}
Wait in raycasting is the second paramater just direction or do we need to define an endpoint (direction * magnitude)
Sounds like you forgot to mark InputManager as public
I don't know... I just started using the new Input system and haven't done anything with the InputManager. How can I do it?
InputManager is your custom class
Oh
It's not part of the input system
Check the documentation for Raycast, it's explained there
in this case does teh second paramater need to be direction * the distance of ray
Or just the direction??
and if so how does that even work is the ray casted to an infinite magnitude or something!!
ok, then I'll need to recheck the YT video. I'm learning on YT so I think I missed something
ah can only see the syntax not an explanation
im confused onto how big the magnitude of the ray is
It shows the default value for that parameter
float maxDistance = Mathf.Infinity
ohh
is there anyway to set the distance??
Yeah, by filling out the parameters
am i on the right page this is really vague
Oh my bad, was looking at Raycast documentation. Ray doesn't include distance
As mentioned you should look at Raycast documentation for how Raycast works. You're looking at Ray
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEditor.Experimental.GraphView;
using UnityEngine;
public class Player : MonoBehaviour
{
public Rigidbody rb;
public float speed = 1f;
private float verticalInput;
private float horizontalInput;
private bool OnGround;
public float jumpPower = 10;
RaycastHit hit;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Ray ray = new Ray(transform.position, -Vector3.up);
if (Physics.Raycast(ray, out hit))
{
Debug.Log(hit.distance);
if (hit.distance > transform.localScale.y +0.1)
{
OnGround = false;
}
else
{
OnGround = true;
}
}
}
private void FixedUpdate()
{
verticalInput = Input.GetAxisRaw("Horizontal");
horizontalInput = Input.GetAxisRaw("Vertical");
transform.Translate(Vector3.right * Time.deltaTime * speed * verticalInput);
transform.Translate(Vector3.forward * Time.deltaTime * speed * horizontalInput);
Debug.Log(OnGround);
if (OnGround)
{
if (Input.GetKey("space"))
{
rb.AddForce(transform.up * jumpPower);
}
}
}
}
for some reason jumping near an edge flings me high up
I need some help
My DDOL varaibles are still resetting when changing scenes and im very confused
!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.
cs??
using UnityEngine;
public class DDOLManager : MonoBehaviour
{
// Singleton instance
private static DDOLManager instance;
// Variables to store
public int score = 0;
public int health = 100;
public bool isLevel2 = false;
void Awake()
{
SetupSingleton();
}
void SetupSingleton()
{
if (instance != null)
{
Destroy(gameObject);
}
else
{
instance = this;
DontDestroyOnLoad(gameObject);
}
}
}
isnt c# and cs same thing
c-sharp
Anyone know whats up?
Uh, looks fine to me, but how are you accessing this instance if you're making it private anyway
My other script
private DDOLManager ddolManager;
void Start()
{
Boundaries();
if (ddolManager == null)
{
ddolManager = FindObjectOfType<DDOLManager>();
}
}
Like the script above
That private instance is just to check if theres more than one
Pls if someone knows issue reply, ty
So, what happens? Does the static instance become null on scene change?
Try logging that if statement at the bottom, see what it does on scene change
Try putting DontDestroyOnLoad(gameObject) in the else statement perhaps
Just see what sticks for now
You should not move a rigidbody object with transform btw. It will result in physics glitches/desync. Use rigidbody.AddForce/velocity/MovePosition
this only allows me to go forward and back??
for some reason A and D just dosent work anymore
when using velocity
Because you're replacing the first assignment of velocity
First you set the right axis, then you replace it with the forward axis
?? what does that mean
Not sure how more clear I can be
You're assigning the velocity, then replacinge velocity completely on the next line
oh yea!!!
Oh i fixed it it was just that I had 2 points variables and i didnt notice
Im dumb
btu then i cant walk diagonally anymore!!
gonna need a conditional for that i
think
No, just combine them
So, there's no issue? 🤔
combine unit vectors then multiply by magnitude??
No my brain just sucks
I was displaying a different variable points cause i forgot to delete it
But the one ^ is a different issue the issue i had before is that i created multiple DDOL objects
But i fixed both now so
Make a new vector3, add the vectors from those two lines to it (transform.right * ... and transform.forward * ...), then set your velocity to that vector you just made
Or just replace the bottom rb.velocity = with rb.velocity += so that it adds to the velocity instead of overriding it
I see this guy refering to BugPrefab directly as Bug but I can only see myself able to refer it to as GameObject. How to do it like this?
What isn't working for you?
https://unity.huh.how/references/references-to-prefabs is my instructions on the topic
i have a prefab in the prefab folder called Slime which is a prefab of Slime monster. However, I want to make another script called SlimeSpawner and make Slime a class and not refer to it as GameObject
oh thanks
wait how is the guy in the video refering to his Bug prefab as a Bug type and not a GameObject type
you dont need to instantiate something of type GameObject, you can refer to any script on the prefab. Instantiate will then return the script on the spawned prefab
Because it's a component of theirs
Yup
Yo guys
To call a method from another script can you take a look at this because its not being called
public void LoadLevel1()
{
SceneManager.LoadScene("GameLevel1");
if (ddolManager != null)
{
// Call the method from DDOLManager
Debug.Log("Variables Reset!!!");
ddolManager.ResetVariables();
}
FindObjectOfType<GameSession>().ResetGame();
}
Also whats this error?
the script seems normal can you screen shot the error
I dont get error
Idk what this one is though ^^
does not say where the error is
have you tried reimporting everything in the asset drop down
Wait i have an idea
That error is usually an editor error. unless you get it often, you can ignore it
Ok so the script Level 1 is being loaded but the other one is not
just reimport things. I guess it is something corrupted
If something was null you would get an error trying to call the method. You should add debugs to see what code is even running
I got another idea!!!!!
Il try putting the reset variables imediatly in the level 1 script
nvm im braindead that dont work
the pain
Instead of randomly trying stuff, add debugs and see what's happening for real. Also you havent really specified what isnt running. Have you checked if there are any other errors (not the unity self one)
Yeah theres no errors
THe reset variables isnt running
This
Hi. I made a counter of how many objects the player collects that have a script: "Note". There is a problem that 1 such object can be added to the counter infinitely times (1 object gives more than once). I tried to think of a way to fix it, and all attempts failed. How can I fix this?
What's the issue with that? Should each object only be able to give one point?
Yes
Then maybe you ought to register acquired items in some sort of collection, such as a hash set.
I think I figured out how to implement it. Thanks
Hi
I want to write my own shader, I have an idea for it. But i'd like to start with a basic one which already implements texture mapping. Do you know where I could find that to start off with?
Try asking #archived-shaders
Just a quick Qestion i have two objects one is null . Can i switch them so obj1 = something obj2=null;
by doing obj1=obj2 and obj2=obj1
ofc with extra var
?
if (obj2 != null) { obj1 = obj2; obj2 = null; }
GameObject tempItem = currentActiveItem; currentActiveItem = backedItem; backedItem = tempItem;
if one of them is null
will it work?
works xD
define 'work'
it wont throw an exception but you still wont know which one is null
shouldnt do that just change
it will swap the objects over, yes. But to what effect?
Is it better to move player through addforce or changing the velocity.
Would it make sense to use it for snappy movement or is that something you can do with addforce
Either works
Ok ty
i saw a guide where someone is storing the orientation of the player (capsulate) in a empty game object. This here confuses me. Why not just grab the orientation directly from the player himself??
another thing is he made a cameraholder object for the player. Why not just directly make the camera follow the player?? These things confuse me
hello good morning do you guys know anyway of killing all animations to go straight to my dying animation when the character dies right now to activate in on any state but for the most part it works fine but the death animation kinda gets messed when in middle of a jump or just started walking
its like a bug
animator.CrossFade() perhaps
ok so im creating an aiming system for my game, and i need the firepoint to switch position when the gun sprite flips
only issue is that this runs every frame, when i want this to only run once per flip
how would i get the commented code to only run once per flip
Check if the new flip value is different than the old one
If yes, run the code that changes the firepoint's position
Why my animation curve doesn't have fixed time 0 1?
You tell us? Drag the end point where you want it to be?
Yeah, I'm stupid
https://medal.tv/games/requested/clips/1INMhX3RDRZNjJ/d1337pUrF1IM?invite=cr-MSxiQ0osMjAzNDI1NDA5LA
as soon as i go in my character goes immediately backwards, why may this be?
pastebin:
https://pastebin.com/JdYwH2k6
Watch Untitled and millions of other Requested videos on Medal, the largest Game Clip Platform.
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 tried to debug.log your movement before anything?
cause your speed is > 0 so
put debug.log inside VelocityLimiter too, see how many times thats called.
Hello everyone, I've just begun my first 2D game project, and I'm still a beginner. I wanted to ask: can anyone advise me on how to start creating movement for my 2D character?
Pretty sure learn.unity.com has a 2d platformer project
2D movement can mean anything
topdown , sideview etc
4 direction , 8 direction, 2 direction
grid movement
I see, I want to implement movement in four directions for my project.
are you sure ?
then google how to do it
yeah the bug only happens when i add the statehandler
it really depends. 2D characters range from super simple to mario.
well , have you tried googling 4 direction movement 2d unity ?
do you have other scripts that depend on it? because the addforce here only gets called with movedir.. if thats not 0,0 tho it could be issue
otherwise im not sure how anything x 0 would be anything but 0
i would start by deciding if you want your object to be kinematic or dynamic. This is probably the biggest factor in how complicated it will be
i dont have any other scripts that depend on it
ok well it doesn't seem statehandler does anything but set states that aren't used anywhere
unless its speed which would probably not be important if AddForce includes moveDirection (assuming its 0 with no inputs)
Debug.Log(moveDirection)
dynamic rigidbodies are at the mercy of the physics engine. they automatically collide with walls etc, and are affected by gravity and forces etc. But programming extremely basic forced motions is difficult (eg making a dynamic RB move along a floor of changing slope), because you have to fight the physics system.
https://youtu.be/xCxSjgYTw9c im following this video if that helps
SLOPE MOVEMENT, SPRINTING & CROUCHING - Unity Tutorial
In this video, I'm going to show you how to further improve my previous player movement controller by adding slope movement, sprinting and crouching. (You can also use your own player controller if you want to)
If this tutorial has helped you in any way, I would really appreciate it if you...
was it working before or ?
it was moving and working before
screenshot the inspector for player, also and what did you do that broke it you think??
i bet it was the part where he adds the enum, and statehandler in the first part of the video
after that it broke
those enums dont do anything right now though
also you should not be grabbing inputs inside FixedUpdate
verticalInput = Input.GetAxisRaw("Horizontal");
did you try Debug.Log what I said
Debug.Log(moveDirection)
i still think it could be VelocityLimiter
do you want me to debug.log velocity limiter too?
sure try that after
yeah some software side stuck
oh nah
i do have
xbox controller
but rn its doing nothing
it doesnt have stick drift or anything
and its still plugged in
cause only way it would b moving on its own if rb.AddForce(moveDirection.normalized moveDir was not 0
I feel like the controller was definitely it
well its fine now
yeah i think it was prob giving a weird signal
maybe controller go to idle or something
Is there a way of making a variable's value invisible in the Inspector but still accessable by other scripts?
can someone help me with something i will tell in dm and in dms i will send unity file
[HideInInspector] + public
It is very very unlikely you will find anyone to do that. Especially without knowing what the issue is and whether they could even help.
You might find a gambler though
oh k am new here
Just ask your question in this channel
can someone hlep me i have problem with colliders player(capsule) fall down even tho theare is plane with colliders on i will send unity file in dm
No need for a unity file
!code share your code, explain your issue. Nobody is going to take it to DMs.
📃 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.
Do both the player and plane have colliders that are NOT set to isTrigger?
public class GameStateController : MonoBehaviour
{
SolvebitController sbGameState;
GuessbitController gbGameState;
SeriesbitController srbGameState;
MembitController mbGameState;
private void Awake()
{ // omitted initialization }
void Start()
{
if (GameParams.game == SelectedGame.Guessbit) gbGameState.Start();
if (GameParams.game == SelectedGame.Solvebit) sbGameState.Start();
if (GameParams.game == SelectedGame.Seriesbit) srbGameState.Start();
if (GameParams.game == SelectedGame.Membit) mbGameState.Start();
}
void Update()
{
if (GameParams.game == SelectedGame.Guessbit) gbGameState.Update();
if (GameParams.game == SelectedGame.Solvebit) sbGameState.Update();
if (GameParams.game == SelectedGame.Seriesbit) srbGameState.Update();
if (GameParams.game == SelectedGame.Membit) mbGameState.Update();
}
// omitted 2 other similar functions
}
How could I rewrite this if all of those classes are based on public abstract class GameController<T> where T: Gamemode. I tried using covariant generics but my base class is not an interface, and it has to be a class
i will check
both have is trigger
Well that is why then
IsTrigger does not collide
They must have that option disabled
huh still doesnt work
Send a screenshot of the inspectors for the player and plane
After that, it may be a code issue
I've been trying to clamp rotations for like an hour- how do I properly do it? right now I'm manually clamping the x y and z values of the euler angles but it only works for positive values
That could be the issue. Does the player have a rigidbody?
You should just send a screenshot of what you think is relevant
So that capsule is a child? Does the parent also have a rigidbody?
yes
Remove the rigidbody from the capsule. Let the parent rigidbody use the collider
I think the parent is falling and updating the position of the child. The childs collider is "used" by its own rigidbody, and won't affect the parent
now i dont fall trough plane but before i land i go diagonaly
Like when you try to move, instead of going the way you want, it moves diagonally to that direction?
Or just moving by itself?
moving itself
You would just do:
GameController gameState;
void Start() {
gameState.Start();
}
void Update() {
gameState.Update();
}```
Note that this will require you to have a non-generic GameController class as the parent class of the generic `GameControllerT` class.
@abstract flax I do notice the child colliders position is not 0,0,0
So it is offset from the parent.
Probably not the issue, but it is a issue
but i need the generic
oh
a generic child
i get what you mean
and then the generic concrete children
But for your issue, is it spinning weirdly, or just moving while keeping the same rotation?
That would be two different issue
If it keeps the rotation, it's gonna be a code issue
If it spins, try freezing the x and z rotations on the rigidbody
GameController
GameControllerT
SolvebitController
GuessbitController
ok
it still countinues to spin
and falls trough plane
and i gtg now
Oh sorry, missed ya.
A couple things to try when you can.
Set the interpolate settings on the rigidbody to interpolate (instead of none)
Set collision detection to continuous.
Freeze all rotations in the constraints
After that, post the movement code as osteel said above
#💻┃code-beginner message
ok
wait but now its missing my methods
i did but still fall trough
i will send code rn
bye now
Ah, you're mixing a charactercontroller and rigidbody.
You gotta choose, don't have both
Also, configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
ok will do that when i come back
you have to put the abstract methods on the abstract classes
Having trouble with an Index Out of Bounds error.
This is the line that the error is being caused by:
char newCh = lowerAlphabet[Array.IndexOf(lowerAlphabet, ch) + shuffle];
This is lowerAlphabet:
public static readonly char[] lowerAlphabet = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
And ch is h, or e or l or anything else in hello world. In this case, shuffle is 6, but I also have this line to account for shuffles more than 26 (this is for a Caesar Cipher):
shuffle %= 26;
Can someone help me out? This is the exact error:
IndexOutOfRangeException: Index was outside the bounds of the array.
This was working before so I don't really know what changed.
clearly Array.IndexOf(lowerAlphabet, ch) + shuffle is out of range of the array
But that can't be possible in this case
you need to modulo that whole expression by lowerAlphabet.Length
why not?
Debugging shows it failed on h
h is index 7 in lowerAlphabet, shuffle is 6. Shouldn't fail.
Right?
you should easily be able to also debug shuffle and lowerAlphabet.Length then
Sorry, I'm not following. Why would I debug lowerAlphabet.Length? That's a fixed number.
So is shuffle.
Debugging is all about questioning your assumptions
clearly one or more of your assumptions is wrong
else you wouldn't have a problem
Ok, fair point. I shall go and try it out
check everything, even the things you think you know are true
How do you know it's a fixed number
It's a member variable and the length of the array is 25, pretty certain that's impossible to be wrong. I'll still test, but I see no way for it not to be the case
oh so i copy each method and make it abstract?
But how have you confirmed that the value you think it is, is the value it currently is
unless you have another local variable by the same name by accident, for example. There are many ways it could go wrong. That's just one thing to check. Just print everything around that expression and you'll find something off.
Ok, will do
you need abstract Update and Start methods for this.
right
That's the only reason I made it readonly 😆 I thought this might happen at some point
Assuming my assumptions are correct, you think this is ok?
char newCh = lowerAlphabet[(Array.IndexOf(lowerAlphabet, ch) + shuffle) % 25];
Can't believe I overlooked this case.
should be % lowerAlphabet.Length rather than a hardcoded number
25 would be wrong anyway, no? 26 right?
Makes sense. But wouldn't that make it 26?
yes
Because of the index, I was thinking
Wait
% 26 gives you a number in the range [0, 25]
@wintry quarry thank you so much!!
took me like a few days to figure this out 😓
now it would be left to store my games in a dictionary
@wintry quarry @polar acorn Thank you both for all the help, turns out my int parsing for the shuffle was wonky - debugging that helped. Thanks!
I have an object moving on the zaxis, if it collides with an obstacle, the obstacle's oncollisionenter will be called, and that calls the gameover function of the object, which is this
alive = false;
animator.Play("Fall");
rb.AddForce(new Vector3(0,0,-50));
Invoke(nameof(Restart), 3);
however, rb.addforce is called, but there is no effect on the scene
does addforce not work outside fixedupdate?
you probably want that to use ForceMode.Impulse
it works now, thanks
can somone help me for a sec...
I am trying to make a small chunk builder, and it "works" so far when I use some tricks... but in the GenerateChunkMap function, I was trying to not have to pass through my public object that I want to spawn, cause I want to spawn multible types and potentially more than I am already am. I want to define this there... essentially... so having to pass it into it is not what I want/need
the paln was to have it like my 4th image (error highlighted) but I don't exactly understand why this is a problem here... seeing that my subclass should have access to the prior public game object, shouldnt it?
I cant make the street_streight static though, as I pass it into my unity script... or am I missing something?
eg... blue-box should be my gameobject that I pass into the script...
you still need to give the class a reference to an instance of the World_Generator class
what subclass? is it derived from World_Generator?
is there a Debug.DrawLine equivalent for drawing on the UI?
pretty sure they are referring to a class declared inside of another class (hence the error about needing an object reference)
I mean... MapChunk is a class of World_Generator
or am I currently sitting on tomatos?
The only builtin way I know is with GL.LINES <--- not anti-aliased, so might not look like you want if it's for UI
Or you can use some asset (like Shapes?)
you need to tell the MapChunk object which World_Generator object you are using
huh, ive never seen GL
Might look a bit confusing but theres an example on the docs
https://docs.unity3d.com/ScriptReference/GL.LINES.html
What render pipeline are you on?
URP
looking at the GL docs it looks like something si up with URP
something about being unable to use OnPostRender()
I am sorry if you need to spoonfeed spoons rn... but huh?
Yeah in URP/HDRP you need to subscribe to one of the beginXXRendering events:
https://docs.unity3d.com/ScriptReference/Rendering.RenderPipelineManager.html
I think beginCameraRendering is what you need
it's not static. you need to tell it which World_Generator object you are accessing that variable from. which means you need to give it a reference
that looks right
alternatively you could just pass the object you are trying to access instead of the World_Generator
I... yes... I could also just pass the list of objects...
head meets desk
thanks
public class MoveCamera : MonoBehaviour
{
[SerializeField] private Camera cam;
private Vector3 mousePos;
private void Start()
{
mousePos = Input.mousePosition;
}
void Update()
{
if (Input.mousePosition != mousePos)
{
moveCamera(Input.mousePosition);
}
mousePos = Input.mousePosition;
}
private void moveCamera(Vector3 mousePosition)
{
Vector3 translatePos = new Vector3(mousePosition.x, mousePosition.y, cam.transform.position.z) * Time.deltaTime;
cam.transform.Translate(translatePos, Space.Self);
}
}
Does anyone know why this code is only moving my camera up and to the right?
because Input.mousePosition is always positive
Seems like you're using mouse position when what you want is the mouse delta aka the amount moved?
Also using cam.transform.position.z in there makes no sense either, should be 0
you are confusing positions with deltas (aka the amount to change by) in several places here.
Input.GetAxis("Mouse X") and Input.GetAxis("Mouse Y")
if (GameObjectExample)
{
}
will it check if the gameobject is active?
No it will check if the reference is not null and not a destroyed instance.
alright
if you want to check if it's active you use https://docs.unity3d.com/ScriptReference/GameObject-activeInHierarchy.html or https://docs.unity3d.com/ScriptReference/GameObject-activeSelf.html
thanks
https://justpaste.it/78b7o/pdf
Can someone help me understand why the weapon doesn’t load when switched
You appear to have several errors in your console
You should probably fix those, it may fix your problem.
It’s the same error
Also why on earth is your code shared as a pdf lol
ok well, sounds like you'll be able to get rid of all of them by fixing the one error then
you should focus on that
Use one of the sites here to share code: !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 error is only caused cuz the weapon doesn’t load when switched to and I have no clue what I’ve coded wrong
you shared an empty link
You have to press "Paste It" at the bottom
then share that link
ok now... share the full error message including the filename and line number from your console
Looks like you have at least two separate errors
both of them are in WeaponSlotManager, NOT in the PlayerInventory script
NullReferenceException: Object reference not set to an instance of an object
RF.WeaponSlotManager.CloseDamageCollider () (at Assets/WeaponSlotManager.cs:64)
very clear error, this is the line:
HandDamageCollider.DisableDamageCollider()
This means HandDamageCollider is null
Meaning it was either never assigned, or it was assiged to null
Which confuses me because if I remove the code for switching weapons everything works fine but when I switch from unarmed to the weaponItem the weapon object doesn’t load and when I attack it gives me an invisible weapon that makes that error
what is the time frame in which Input.touchCount works? like if i touch the screen two times in the span of a second, will it count those two?
Why are physics behaving different in webgl and in windows?
Did you put physics code in Update
What do you mean by "doesn't load"?
Presumably either:
LoadWeaponDamageCollideris never running
orHandSlot.currentWeaponModel.GetComponentInChildren<DamageCollider>();is returning null (or throws an error of its own)
You need to debug to find out which
yes
The frame you call it in
It is how many touches are currently happening right now
Ahh yes, you are right. Sorry my bad!
´´´cs
How do i make it so when i press e and im not grounded the camera quikcly zooms in and out???
`using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Dash : MonoBehaviour
{
public float dashDistance = 5f;
public Camera cam;
private CharacterController controller;
private PlayerMotor playerMotor;
public float dashTime = 0.5f; // Duration of the dash
public float zoomFOV = 60f; // Adjusted FOV during dash
private float originalFOV;
private float dashTimer;
void Start()
{
controller = GetComponent<CharacterController>();
playerMotor = GetComponent<PlayerMotor>();
originalFOV = cam.fieldOfView;
}
void Update()
{
zoomFOV = cam.fieldOfView - 10f;
if (Input.GetKeyDown(KeyCode.E) && !playerMotor.isGrounded)
{
Foward();
cam.fieldOfView = Mathf.Lerp(zoomFOV, cam.fieldOfView, 10); // Smoothly restore FOV
}
}
private void Foward()
{
Vector3 dashDirection = cam.transform.forward;
Vector3 dashVector = dashDirection * dashDistance
controller.Move(dashVector);
}
}`
!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 weapon model doesn’t appear when switched to
yes because you have errors
you need to fix the errors, that's what I was helping you with
Oh right
this is my code but unity says Member modifier private must precede the member type and name am new to unity if anyone can help me
First off you need to configure your !ide so you can get error highlighting and autocomplete
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
does anyone know shader graph??
oh thank you
The issue is with missing semicolons, and a missing variable name
The ide being configured will help resolve that
i configured ide
Do you have red underlines in the code now
Especially if you're following this particular tutorial, you're going to want to take it much slower and be a lot more careful about how you spell and capitalize things. You're being a bit careless. Configure your IDE and copy everything exactly
it changed a bit my code and i got giant red chunk of code
Yep, so it's configured
Take a look at the lines underlined in red and compare them very closely to the tutorial
and once i do ?
i replace stuff with red code?
You fix the problem you see
For example, if your code doesn't have a semicolon and theirs does, then add the semicolon
am oofed i have 80 lines of red code
probably a small error near the beginning of the 80 lines
likely a minor issue with brackets or semicolons or parentheses etc
I don’t even know how debugging works but I don’t know how to solve it
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestScript : MonoBehaviour
{
private List<IEnumerator> coroutineList = new List<IEnumerator>();
// private int currentCoroutineIndex = 0;
int difficulty1;
int difficulty2;
int difficulty3;
bool routineRun;
// Start is called before the first frame update
void Start()
{
coroutineList.Add(Pattern1());
coroutineList.Add(Pattern2());
coroutineList.Add(Pattern3());
StartCoroutine(CycleCoroutines());
// StartCoroutine(Pattern1());
}
// Update is called once per frame
void Update()
{
print("1: " + difficulty1);
}
IEnumerator CycleCoroutines()
{
while (true) // Infinite loop
{
print("looping");
foreach (var coroutine in coroutineList)
{
print("for loop");
StartCoroutine(coroutine);
yield return new WaitForSeconds(1);
}
}
}
private IEnumerator Pattern1()
{
//routineRun = false;
print("reaching while loop 1");
while(true)
{
print("hello");
difficulty1++;
yield return new WaitForSeconds(2);
if (difficulty1 == 2)
{
difficulty1++;
break;
}
print("pattern 1");
}
}
private IEnumerator Pattern2()
{
while (true)
{
difficulty2++;
yield return new WaitForSeconds(2);
if (difficulty2 == 2)
{
difficulty2++;
break;
}
print("pattern 2");
}
}
Im trying to make an infinite loop which loops through all the patterns i have in the game. Right now it just loops one then get stuck in the first loop
Debugging is simply the process of investigating and solving the bugs in your code. Good tools for debugging include adding log statements and attaching a debugger to inspect values while the code is running
If you are trying to wait for the other coroutine to continue before starting a new one you need to do yield return StartCoroutine(..)
I had it like that before but same issue
start debugging
oh also you can't reuse an IEnumerator
it just starts infinite looping in the CycleCoroutines() loop forever and stops printing inside any of the Patern functions
right you can't reuse an IEnumerator
So should i make it a normal function instead?
once you call StartCoroutine on it once, you can't do it again
no...
LMAO
you just need to call the function again to get a new IEnumerator
So i keep recalling the Cycle function?
no
instead of List<IEnumerator> you can make it a List<Func<IEnumerator>> and put the functions themselves in the list
and invoke them in the loop
like StartCoroutine(coroutine());
I see, is there a simpler way?
this is very simple
i see
you would need to change approximately 3-4 lines of code here only very slightly
Ye?
Could u maybe potentially help me with finding out which lines?
I already told you
The whole explanation of what to change is here
Arent i already inserting the functions in?
so i just add Func generic there and im good?
no you're inserting the IEnumerator objects that the functions return when you call them
OHHH
ok
Adding the IEnumerator to the list:
coroutineList.Add(Pattern1());
Adding the function itself to the list:
coroutineList.Add(Pattern1);
Hmmm its giving me red lines
List<Func<IEnumerator>>
i tried adding this in
but it didnt work
Why Func?
He said to make it so it stored the action function instead of the return
Oh, I see that. You're right.
What is the error?
got a better idea?
I said "Oh, I see that"
And no. I just thought praetor said something else earlier
What is the error?
lemmie get that for u rq
gimmie 2 secs
Severity Code Description Project File Line Suppression State
Error CS0246 The type or namespace name 'Func<>' could not be found (are you missing a using directive or an assembly reference?) Assembly-CSharp C:\Users\alltg\DF 2.0\Assets\Scripts\Enemy\TestScript.cs 8 Active
Holy shit my Internet died
you're missing a using directive
Hmmm, do you have using System at the top?
I am
Very weird
I get the idea but for some reason it just does let me set func
Share the !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.
I'm not home right now but it's this, I replaced the list initialisation with the func generic and removed the brackets from the coroutine list arguements
If I have a bunch of AI units spawning, and I want them to start moving somewhere, right now I pass a single "targetLocation" position for them to move towards, however, obviously this looks super bad with a mass of things all going to the same point, what's a good starting point to try and have them have a better distribution of their target location? There's gonna be ALOT of units, so I don't really want to use navmesh's for this that sounds like it would be unscaleable unless I devoted a lot of time to it.
you need a function that does formation handling
basically take all the units you have selected, take the destination point, and use some kind of formation logic to give each of them a slightly different destination point
You almost definitely will want to use NavMesh or some kind of pathfinding algorithm
you will need this to make sure all the destination points are valid
oh sorry to be clear, these units spawn, and individually, they have a target location and they just start moving towards that location (its enemy zombies moving towards your like...base wall, I just want them to not all move to the same point) though I see still how what you're describing could work
I just want them to not all move to the same point
I mean that's pretty self explanatory - pick different points for them
or have them pick at random from a set of valid destination points
yeah so at the end of the day its still just manage a handful of nodes, I can't create a more generic...thing, okay that makes sense
hello. if i was to use materialNameHere.SetColor(xxx,ExampleColorHere) on the same material but on different objects and within different independent scripts, will it change the color of the material on a per object basis or does changing the color of the chosen material attached to the renderer change the whole materials color so it ends up being the same on every object with that same material? sorry if I've worded this poorly, its hard to articulate
materialNameHere
This is the important part
it's not a name of a material, it's a reference to the material
so it really depends which references you're using and where you got them from.
in this instance it would be: pixelOutlineMaterial = GetComponent<Renderer>().material;
ok so
you need to read this:
https://docs.unity3d.com/ScriptReference/Renderer-sharedMaterial.html
and this:
https://docs.unity3d.com/ScriptReference/Renderer-material.html
and understand the difference.
oh sweet, so I can use it as a shared material or a (non shared) material
I'm making my first game rn. It's a simple game with a cube that shoots bullets at enemies. I'm having trouble with the bullets dealing damage to the enemies, as the enemies arent losing health or being destroyed when health is 0. Here is my code:
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class EnemyScript : MonoBehaviour
{
// Start is called before the first frame update
public int Health = 5;
public int MaxHealth = 5;
public GameObject Enemy;
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.name == "bullet(Clone)")
{
Health = Health - 1;
if (Health == 0)
{
Destroy(Enemy);
}
}
}
}
You should add some Debug.Log statements to the collision method.
This will tell you if the method is getting called at all, or if that if statement is succeeding
more generally, check out https://unity.huh.how/physics-messages
it walks you through all of the possible problems
The code looks OK to me, so I'm guessing your problem lies elsewhere.
also you really shouldn't rely on gameobject names for logic. i'd recommend using a tag and the CompareTag method instead
yes, indeed, other than that :p
alternatively, the bullet should have a "Bullet" component
you could even make bullets that do more damage
yea but when the bullets spawn they spawn as Bullet(clone)
using names is very fragile
how would i implement that?
do note that Bullet(Clone) is not the same as bullet(Clone)
it's fine for beginners, it'll click at a certain point, i'd recommend just making a giant mess of your first project, you'll learn a lot more actually getting things to move around and interact.
anyone can help me question mark text toggle like
when i press the question mark and it appears the text for like 5 or 7 seconds and the text is gone
its spawns as the latter
anyone know why my instantiated bullet game object won’t move while the object sitting in my schene moves with velocity (this is for 2d using dynamic)
not without more info
well, at this point, things aren’t moving around and interacting 😅
Does the bullet have a script on it telling it to move?
Do I need to know how to code to make a game?
Yes
Depends on the game but as a safe bet yes
No game will require no code
What type of code?
At least a version of coding if you include scratch
C# is what Unity uses
Are there courses that are free or affordable?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
yeah
You gotta provide more info, show the script and show the bullet in the inspector
but the prefab i put in my scene works as normal just not when i instantiate it inside of the rb2d of the player
Show the bullet in the inspector at runtime and its movement script. Also show the script instansiating it, is it instansiating the correct prefab?
i will when i get home thanks bro
I revised it but it still aint working...
{
if (collision.gameObject.CompareTag("bullet"));
{
Debug.Log("ENTER");
Destroy(Enemy);
}
}```
maybe ill try using an actual collider
put a log outside of the if statement to make sure that OnCollisionEnter2D is actually being called
oh wait, it's already outside the if statement
if you don't have an "actual collider" this code is definitely NOT running.
Also yes your if statement is broken
because you put a semicolon after the condition
I tried adding circle colliders to both bullet and enemy, since their circles
swapped OnCollisionEnter2D for OnTriggerEnter2D
If you want OnCollisionEnter2D you need:
- at least one of them to have a dynamic Rigidbody2D
- Both need colliders
- neither collider should be a trigger
If you want OnTriggerEnter2D:
- At least one has a dynamic or kinematic Rigidbody2D
- Both need collider2ds
- At least one collider is a trigger
CharacterController works for OnTrigger too
Yeah I was just about to say I missed the 2d, sorry
show:
- the current code
- screenshots of the inspectors of the two objects you expect to collide
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
@polar acorn
You're moving via teleportation. That's not going to have any sort of collision. If you're using the rigidbody for some movement, you need to use it for all of the movement
how i can fixe it ?
Use the rigidbody to move
Hello! I'm trying to understand how to make a roof tilemap fade when the player enters a house.
Its TopDown 2D
in the scripte or what ? @polar acorn
You can use this to set the color (including alpha) of a particular tile: https://docs.unity3d.com/ScriptReference/Tilemaps.Tilemap.SetColor.html
Thanks
Hello, I am making a game with some weapons I have picked up from the asset store. I have parented the weapon to the characters right hand for the animations to work properly but for one of the weapons the animations alternate where one animation requires the character to hold the weapon in the right hand while the requires to hold in the left hand. Is there any way for me to change the parent(hand) of the weapon when the different animations play?
Why doesn't this code work? cs private void OnTriggerEnter2D(Collider2D collision) { if (tilemapCollider) { print("Hit"); } }
What are your intentions?
Is tile map collider null?
Is the physics event occurring?
Try printing outside of the if statement.
Probably a misconfigured scene or prefab
im staring at unity code and i keep seeing plus equals be used to poll events with the new input system. Why?
how does this work?
Hi guys
How are you?
I was following the retro fps tutorial and I'm having a problem with my enemy's code.
He is able to see the player through the wall, I tried using raycast to solve this, but I still have the problem.
My code currently looks like this and when the player gets close to the enemy the console prints "Nothing", even though the player is in front of the enemy or behind a wall, does anyone know how to solve this?
+= is the syntax to subscribe to a delegate in C#
delegate? whaaa
C#'s version of function pointers / events
this particular snippet means "run this function defined on lines 2-5 whenever the onActionTriggered event is fired"
This isn't pointers in any sense like you're thinking of with C or C++
I understand how to set parent through script but how do I do it only when the specific animation plays
well it is but you don't need to worry about it
anyway if you're doing programming you have to deal with pointers at some level full stop lol
Use an animation event? or even just set the parent IN the animation itself
how to change moving via teleportation to rigidbody in this code ?help
I am sorry I am really a beginner, when I put this script as an animation behaviour it didnt let me choose a game object at all
I just want the tilemapCollider to function as collision. So it triggers the Print function.
Hello I would like to learn coding, does anyone have any simple tutorials that would give a good start?
The collision works, its just the tilemapCollider not working, or any collider that isn't collision. Also I have assigned the tilemapCollider.
wdym "the collision works"? You were asking about your code "not working". You didn't explain what that means
The "collision" from the function works. But when I try to use any other collider such as an BoxCollider on a object, it doesn't work.
what does "doesn't work" mean
what are you expecting to happen?
What happens instead?
The interaction isn't happening. When I move into the box, it doesn't print("Hit"). Nothing happens.
BoxCollider is not a 2D collider
It is a Boxcollider2D
Ok, so show the inspector of both objects involved in this interaction
the full inspectors
of both objects
need to see more than this
Also explain which script has the above code
The "ChangeTiles" has the script @wintry quarry
The ChangeTiles object doesn't have any collider at all
nor a Rigidbody2D
If you want OnTriggerEnter2D to run, you need:
- A Rigidbody2D on one of the objects
- Both objects have a Collider2D
- At least one of the colliders is a trigger
It's also unclear to me what the point of the "Tilemap Collider" field on the ChangeTiles script is for. Seems relatively pointless
hey. Is it better to start learning with 2d or 3d?
oop thank you
Doesn't matter too much. Rotations are a bit more difficult to wrap your head around in 3D but most of the concepts are the same
my first application was 2d jus to learn about gameobjects and whatever.
honestly suggest that first jus to get the basics of that down
3d shouldnt be that much of a challange after
Okay thanks. Sooo i start with 3D
ooo. Thank you too!
I'd probably start here:
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
FREEEE thats nice Thanks!
I have all the qualifications to have it work. Are you sure it's not just something I missed in the code?
Fromt he screenshots you shared before, you don't.
If you changed things, please share new screenshots
Why doesn't this code work? cs private void OnTriggerEnter2D(Collider2D collision) { if (tilemapCollider) { print("Hit"); } }
I thought it might be something after stating the collider
Because, as per what you shared before, you don't have all the things you need on the objects for OnTriggerEnter2D to run
For debugging purposes for now you should also just have a Debug.Log OUTSIDE any if statements in the code.
I have a player with collider/rigidbody
show screenshots
I can't currently. Ill try to resolve this issue later. Thank you for the help!
The code looks fine (although you aren't using the collision reference at all). Your unknown unwanted behavior lies elsewhere.
@polar acorn plz later show me how i change it
Okay, what about this situation? You have two objects with boxcollider2d and rigidbodys. One of the objects has multiple colliders so you need to only reference the boxcollider2d. What can this look like in code?
private void OnTriggerEnter2D(Collider2D collision)
collision would be the collider that was triggered.
Hello.
Why is this error is coming? When I click download on any package, in Package Manager. This error comes. Help me please. I'm using Unity 2021.3 LTS.
You're not the only one
something's wrong with it right now
Okay. Thanks for the info.
fucking Unity fix your shit please
trying to install some stuff through package manager!!!
how often does this happen @wintry quarry
Does beginner coding truly come here for starting?
From time to time. I work for a Saas company myself. I'll let you know that every cloud based software service has occasional downtime. ¯_(ツ)_/¯
that what k8s are for tho
Even with k8s
multiple clusters tho plz unity
k8s is a double edged sword. It can actually make it super easy to screw shit up very fast 😉
a let down for sure, when you have time blocked out to do something
Absolutely! Downtime sucks! What's worse is their status page shows all is green: https://status.unity.com/
Maybe someone needs to mean tweet them
.... not what I like to see
As an additional data point I just tried to download an asset and got the same error
You can ask beginner questions about coding here, yes
Alright, least in the right spot
Needing to learn coding kinda soon but effectively but I’ve ran into the issue that after trying to study a video explaining stuff, brain sorta tunes out after a while
And one video I was watching about first person movement but I am mainly trying to go for 3rd person movement and that
Did you learn how to use c# first?
Nope
Yes I did.
is there anyway to manually import packages?
or do I have to wait for Unity to wake up from their deep slumber
i'm attempting to make a simple top down shooter. The code for the actual firing, works but constantly fires without the press of "fire1"
Sounds like a code issue. Share your script?
How do I do that again, it's been a while since i've worked on anything
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
public class shoot : MonoBehaviour
{
public Transform firePoint;
public GameObject bulletPrefab;
public float bulletforce = 20f;
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Fire1")) ;
{
Shoot();
}
}
void Shoot()
{
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
rb.AddForce(firePoint.up * bulletforce, ForceMode2D.Impulse);
}
}```
if (Input.GetButtonDown("Fire1")) ; You have a semicolon here
you should be getting a warning about this in your code editor
My IDE doesn't seem to do that all the time, I have set it up with the instructions here several times with little to no change.
You're going to have a huge amount of trouble learning this without a configured IDE.
I've simply missed it, it was telling me i was just not paying attention.
My mistake.
Any luck yet
what package are you trying to add? you might be able to add it via git url instead
Is the package on GitHub?
the option is here, im unsure what the git url is as i havent used fishnet
I will try! Thank you for the info
playerLayer = LayerMask.NameToLayer("player");
this doesn't setup the correct layer for a raycast, how would I do it correctly?
Any coders with adhd who able to provide coding assistance? Genuinely need the aid
And I’m excited to get started on my project I’m motivated to get it started
LayerMask.GetMask to create a layermask
note the difference between a layer/layer index and a layer mask
ok and for setting the layer I still use nametolayer?
because layermask is only for raycasting
If you want to set the layer index of an object, sure you can use NameToLayer
that's less common
well when I set
gameObject.layer = objectLayer
when objectLayer = LayerMask.GetMask("object");
I get A game object can only be in one layer. The layer needs to be in the range [0...31]
UnityEngine.StackTraceUtility:ExtractStackTrace ()
How else would I do it?
private void RotateCamera()
{
Vector2 rotationInput = PlayerInputManager.Instance.RotateCameraInput();
float horizontal = rotationInput.x;
float vertical = rotationInput.y;
Vector3 rotation = new Vector3(vertical, horizontal, 0f);
rotation.z = 0;
transform.Rotate(rotation);
}
Might someone have a clue to why my camera still rotates on the Z axis, ive done this many times and first time running into this problem
Now you're trying to set a layer to a mask
again there's a difference between masks and layers
if you want to set the layer, use NameToLayer
if you want a mask, use GetMask
is it actually rotating on the z axis, or are you just seeing the z change in inspector? Because rotations are stored in quaternions, it has to convert to show you it as eulers in inspector. That conversion may result it in saying it has some Z rotation, there are multiple euler angles that result in the same orientation
because euler angles are not unique and there's no way to isolate a single axis when using euler angles
ah so dont use euler anlges
or at least don't rely on them for information
you're seeing a "z" rotation in the inspector, that doesn't mean much
note that rotating on the x axis, then the y axis is equivalent to rotating on the z axis
maybe a better thing would be if you step back and explain what you're trying to accomplish
you can still use it here, try it with 1 axis at a time (remove either vertical or horizontal) and it should rotate correctly visually
Im doing a third person camera, which ive done before cant really figure out why im having issues now, im just trying to rotate on the X and Y axis and Zed shouldn't be rotated on, which im coming to the result of the Z axis also rotating. Which the camera does have a pivot point set in the center of the player
the normal approach is to use two objects
the child rotates on local X
the parent on Y
why when I make a folder in my assets folder in project can i not delete it?
it keeps magically coming back
Yeah now it works thanks for bringing that to my attention
Are you using dropbox or google drive or something
im so fed up with this
Question about rendering something in code and culling. Lets say I render a surface (in this case an ocean) as a two dimensional array of tiles. As I move around the world do I need to figure out which tiles are in the cameras field of view and only render those myself, or will URP figure that out and cull them for me?
An example:
using UnityEngine;
public class CreateOcean : MonoBehaviour
{
public GameObject oceanPrefab;
private static int tileSize = 10;
private static int xMaxOcean = 100; // multiple of time size, even or odd tiles
private static int zMaxOcean = 100; // multiple of tile size, ideally an odd number of tiles to center on start
private float yOcean = 0f;
private static int xDim = xMaxOcean / tileSize;
private static int zDim = zMaxOcean / tileSize;
private GameObject[ , ] oceanArray = new GameObject[xDim, zDim];
void Start()
{
//return;
int i=0, j=0;
int xOffset = 40;
for(int x=xOffset*-1; x<xMaxOcean-xOffset; x+=tileSize) // Start line is @ x=0. Begin the ocean behind start line.
{
Debug.Log("Array element: [" + i + "," + j );
for(int z=zMaxOcean/2*-1; z<zMaxOcean/2; z+=tileSize){
Debug.Log("Loop Iteration: " + x + "," + z);
Debug.Log("Array element: [" + i + "," + j );
oceanArray[i,j] = Instantiate(
oceanPrefab,
new Vector3(x*-1, yOcean, z*-1),
Quaternion.identity,
transform
);
oceanArray[i,j].name = "OceanTile_x:" + (x).ToString() + ",z:" + (z).ToString();
Debug.Log("Name: " + oceanArray[i,j].name);
j++;
}
i++; j=0;
}
}
}```
if each tile is an individual renderer, they will be culed automatically by Unity's frustum culling
Okay thanks very much.
How can i detect two touches on a screen in the span of like a second?
Instead of it being in a frame
cache the last input time then compare on second touch
How do i cache something?
Like put it in a variable?
yep
i have some really simple code here attempting to move the y axis of an object with the y axis of a camera. for some reason it seems like the y rotation is being normalized in some weird way. does anyone know how to mitigate this
cam rotation changes values between these two outputs?
you shouldnt directly use the .y on your rotation, because it is a quaternion. the values aren't gonna be what you expect them to be. You should use the euler angles if you do it this way
love hate relationship
Hi. I want to change the tag of the "Note" object to "!Note", after pressing the "F" key. I tried to find it on the internet and try it myself, but nothing worked. How to do it?
is this code in a Unity event?
Do you mean Void Update?

