#💻┃code-beginner
1 messages · Page 470 of 1
thats harrasment i just want to make sure that people are able to get the help they need from this server
Using the log sashok provided earlier will tell you what the ray has hit
as i hope i will recieve
i think i figured out what its hitting
gulp, I have a bad feeling....
i have a capsule thats a physical object meant to allow me to see where the game controller is
kay hold on
yeah its the player position object
i dont even know what to do about that
i mean the quick and obvious solution feels like just deleting the object, but then i wont be able to tell where the player is
You can use layers instead of tags, and pass a LayerMask to the Raycast, that will tell it to ignore everything except the layer you've selected
so tags bad
In your specific case, layers are a better solution
okay i dont know how to handle layers for this, i'll be right back
Avoid GPT for pure code generation, instead rely on online documentation.
GPTs are not intelligent, they spit out code to look like what they were trained on, and make mistakes sometimes
Thank you kind and handsome friend
I would only recommend using ChatGPT if you know what you are doing. For example, if I have a struct and I need to quickly create a property drawer with buttons in the Inspector for it, I give a fast request to ChatGPT. But since I know how to do it, I will be able to correct the mistakes and rewrite some parts to match my style, and this way, it will be the same as without AI, but faster
Thank you kind and handsome friend
also amazing
Only use it if you know how to implement it without it, but when writing code, which is new to you, I would definitely recommend using Stack Overflow and docs, since ChatGPT is usually not that reliable

im just looking at the documentation for layermask and i just noticed that it separated the physics function into fixed update
https://docs.unity3d.com/ScriptReference/LayerMask.html
Yes, since it's physics
Right, because all physics-related stuff should happen in Fixed Update
the unity docs often dont use the best practices, its mainly just to show the code. Their example checking for input in fixedupdate is horrible
It's a physics query applied once and where results are returned immediately, it does not need to be in FixedUpdate
What?
oh i have to get up in half an hour anyways damn
how do i define the rate for fixed update
raycasts dont need to be anywhere specific. It depends how you're using the raycast or the result of it.
Like if you want something to move in the world respecting physics then it'd make sense to use fixed update
you dont, its already defined to be 50 per second
You don't worry about this and keep your code where you raycast in Update.
You just need to create a layer in Unity, a LayerMask in your code, and pass the mask to the Raycast.
And change the layer of the interact object, of course
might be getting there
ah
found problem
a single bracket did that
IT DISAPPEARED
THE OBJECT
okay its still there
i can walk into it but the moment i added the layer it turned invisible
Layers do not turn objects invisible by themselves
mine might be a lil magical
Some code is doing that, maybe the SetActive() call in your script targeting the wrong object?
Also what layer did you choose?
Which is named?
Interactable
Good, on your main camera make sure this layer is rendered, it's a setting on the Camera component
you are not fool you are great friend
thank you
unity unexpectedly hits me with new problems i didnt even know could be problems
public void PackagePickedUp(GameObject package)
{
Vector3 localPosition = spawnArea.InverseTransformPoint(package.transform.position);
if (col.bounds.Contains(localPosition))
{
packagesInSpawnArea.Remove(package);
currentPackageCount--;
Debug.Log("Picked up in bounds");
}
Debug.Log("Picked up");
}
public void PackageDropped(GameObject package)
{
Vector3 localPosition = spawnArea.InverseTransformPoint(package.transform.position);
if (col.bounds.Contains(localPosition))
{
packagesInSpawnArea.Add(package);
currentPackageCount++;
Debug.Log("Dropped in bounds");
}
Debug.Log("Dropped");
}
I cant get the code in the if statements to execute, do I need to be looking in the local space or world space? I tried both but I just cant get stuff to work
how do i apply a function to only the thing the raycast is hitting, and not all things that have that LayerMask?
show code, because it would be a lot harder to accidentally apply code to everything on a certain layer compared to just the object the raycast hit
The bounding box of the collider seems to be in world space:
https://docs.unity3d.com/ScriptReference/Collider-bounds.html
It might help you if you actually debugged the variables you are working with
it also wouldnt make sense for a bounding box to be in local space.
Bounds https://docs.unity3d.com/ScriptReference/Bounds.html has no knowledge of your object, and it is not a component so it doesnt even have access to your transform
can someone help me i am making a game on unity and i want my monkey to throw bananas but its not working i made a firepoint and put it where i needed to on the attack part and i did object pooling and put like 10 bananas at that area as well where they are all hidden so im not sure whats wrong but heres the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BananaThrow : MonoBehaviour
{
[SerializeField] private float speed;
private bool hit;
private BoxCollider2D boxCollider;
private float direction;
private float broke;
private void Awake()
{
boxCollider = GetComponent<BoxCollider2D>();
}
private void Update()
{
if (hit) return;
float movementSpeed = speed * Time.deltaTime;
transform.Translate(movementSpeed, 0, 0);
broke += Time.deltaTime;
if (broke > 5) gameObject.SetActive(false);
}
private void OnTriggerEnter2D(Collider2D collision)
{
hit = true;
boxCollider.enabled = false;
}
public void SetDirection(float _direction)
{
broke = 0;
direction = _direction;
hit = false;
boxCollider.enabled = true;
gameObject.SetActive(true);
float localScaleX = transform.localScale.x;
if (Mathf.Sign(localScaleX) != direction)
localScaleX = -localScaleX;
transform.localScale = new Vector3(localScaleX, transform.localScale.y, transform.localScale.z);
}
private void Deactivate()
{
gameObject.SetActive(false);
}
}
this is the banana throw code
and this is the monkey attack code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MonkeyAttack : MonoBehaviour
{
[SerializeField] private float cooldown;
[SerializeField] private Transform firePoint;
[SerializeField] private GameObject[] bananas;
private MonkeyScript playerMovement;
private float cooldownTime = Mathf.Infinity;
private void Update()
{
if (Input.GetMouseButton(0) && cooldownTime > cooldown && playerMovement.canAttack())
Attack();
cooldownTime += Time.deltaTime;
}
private void Attack()
{
cooldownTime = 0;
bananas[FindBanana()].transform.position = firePoint.position;
bananas[FindBanana()].GetComponent<BananaThrow>().SetDirection(Mathf.Sign(transform.localScale.x));
}
private int FindBanana()
{
for (int i = 0; i < bananas.Length; i++)
{
if (!bananas[i].activeInHierarchy)
return i;
}
return 0;
}
}
!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.
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class MonkeyScript : MonoBehaviour
{
public float speed;
private float move;
public float jump;
private Rigidbody2D z;
public bool isJumping;
//scale values of monkey
float zy = 0.56f;
float zx = 0.53f;
// Start is called before the first frame update
void Start()
{
z = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
//movement
move = Input.GetAxis("Horizontal");
z.velocity = new Vector2(speed * move, z.velocity.y);
//jump
if (Input.GetButtonDown("Jump") && isJumping == false)
{
z.AddForce(new Vector2(z.velocity.x, jump));
}
//change directions
if (move > 0.01f)
transform.localScale = new Vector3(zx, zy, 0);
else if (move < -0.01f)
transform.localScale = new Vector3(-zx, zy, 0);
}
private void OnCollisionEnter2D(Collision2D other)
{
//ground check
if (other.gameObject.CompareTag("Ground"))
{
isJumping = false;
}
}
private void OnCollisionExit2D(Collision2D other)
{
//ground check
if (other.gameObject.CompareTag("Ground"))
{
isJumping = true;
}
}
//attack
public bool canAttack()
{
return move == 0;
}
}
and this is my movement code jump code and ground check and the start of the canAttack
How to post !code (use the large code blocks guide rather than the inline guide)
📃 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.
can anyone help thanks
Could you listen to the help attempt? Thanks.
Hello, so im trying to make player look in a certain direction on start. When I press start, my camera is reset to 0 and looking in the direction the mouse was last left at on the screen(ex. If mouse was top left of screen on start, the first person cam will be looking top left).
https://gdl.space/etapuxitoy.cs
i tried getting rid of cursor lock but it didnt help
https://gdl.space/uxaziwezay.cs
this script is attached to the camholder and Transform cameraPosition is on the player
If you are unsure what's wrong then debug the code. http://unity.huh.how/debugging
Then post what the problem is if you don't understand still.
the box here is my player, for some reason when im on the wall and hold down the key that goes to the wall(in the pic i held down a to go left to the wall) my player just gets stuck vertically, no gravity, it returns to normal when i release the key though
void Update()
{
horizontal = Input.GetAxisRaw("Horizontal");
if (isGrounded() && Input.GetButtonDown("Jump")) {
rb.velocity = new Vector2(rb.velocity.x, jumpSpeed);
}
}
private void FixedUpdate() {
rb.velocity = new Vector2(horizontal*speed, rb.velocity.y);
}
private void flip() {
if (facingRight && horizontal < 0f || !facingRight && horizontal > 0f) {
facingRight = !facingRight;
sprite.flipX = facingRight;
}
}
private bool isGrounded() {
return Physics2D.OverlapCircle(groundCheck.position,0.2f,groundLayer);
}```
the tilemap uses a tilemap collider and a composite collider
public void PackagePickedUp(GameObject package)
{
if (col.bounds.Contains(package.transform.position))
{
packagesInSpawnArea.Remove(package);
currentPackageCount--;
Debug.Log("Picked up in bounds");
}
Debug.Log("Picked up");
}
Yea I had this but the if statement is not called
Then it's probably not in the bounds. Did you try debugging the involved values?
This is normal, and it doesn't mean there's no gravity. This is happening due to friction
ohh
In real life you wouldn't be able to magically push against the wall in the air like that
if the gameobject is being passed?
What?
i cant find the friction parameter lol, i must be blind
i didnt understand which values you mean
Debugging the involved values:
- the gameobject
- the bounds position and size
- the position of the object
first is the position of the object and second the col.bounds
maybe i pick it up too fast?
yep, thanks for the help, i fixed it:)
this isent about coding but does anyone know how to share a project with a friend i have look everywhere but have found nothing to help
The bounds are just 0.04 thick and are around 1 on the y axis. Yet the position of the object is 2.3 on the y axis. That is outside the bounds.
Maybe try visualizing the bounds with gizmos to make it easier to debug such issues.
The simplest way is just to send them the project folder.
But a more prefered way is using a version control system.
should they be thick as the object?
oh i get it now
gonna have to rewrite the pickup because then i cant pick them up, the trigger of the area blocks it so it cant access the collider of the item
keep the debugging practices up! get in habit of printing actually helpful values too instead of just reached here
you likely won't have any further issues with this specific system, but learning to deal with each issue/case will be easier once you're into the My code WILL have bugs mindset
of course we're going for the perfect system right off the bat, but let's face it it's not likely to happen xD
in your case the Scene view had all the necessary info regarding why the pickup doesn't work (-- you can see the "Scene" even if you're in "Play" mode).
where do you send the project folder?
To your friend.
yeah but like how i tried using gmail but that didnt work
I mean, it could be several GB in size. You can share it however you like. Google drive is one option.
But as I said earlier, version control system would be better.
I'm not sure gmail allows you to share files of such size.
What "didn't work" though?
it deleted the whole file when i sent it to my friend
he just got a gmail with nothing
Well, I'm not sure if we can help you with gmail issues here, but it's probably the size limitation as I mentioned.
Yea I got it to work before but not the way I wanted to
I got it to work now one time but it just wont detect it again
they spawn on the min y of the bounds
so they should be in it
someone help im kinda new at unity but how to u make the object move around smoothly
this is what i mean its a vid
which of these are the trigger? Use a sphere or something for a trigger until you make it work lol
was just gonna say I got it working, it was that it goes into the hand too fast
so thats why its out of bounds
Do not crosspost
by the time function is called its out of bounds already
what
nice
You posted in multiple channels of the same thing
it was only 2
Yeah dont do that
i am now using version control system but i get errors when i go anywhere
Also read what I said in #💻┃unity-talk
When you go anywhere? Like in real life or?
Might want to provide a better explanation
when i press on for example attributes i just get an error saying "the specified repositry couldn't be found: then my project name"
You moved the repository file location
It should say locate or something along those lines
If you click that you will need to go to your rep folder
how i just downloaded the version control system
What application are you using for git
We have no clue what you're talking about. What version control system did you "download"?
Maybe take screenshots if it's hard to explain in words.
unity version control
If you use unity version control and not the unity engine you need the Desktop Client so no you do not need this
You still dont need it even if it's highly recommended from you
Ok, my bad. You might need to download the client, not the version control system.
What I'm trying to say is that they should be providing more info and be more clear as to what they're doing and what problem they have.
Because so far it was like half guessing. Really annoying.
using UnityEngine;
public class CharacterMovement : MonoBehaviour
{
public float speed = 5.0f;
public float jumpHeight = 2.0f;
public float gravity = -9.81f;
private CharacterController controller;
private Vector3 velocity;
private bool isGrounded;
public Transform cameraTransform;
void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
isGrounded = controller.isGrounded;
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 cameraForward = cameraTransform.forward;
Vector3 cameraRight = cameraTransform.right;
cameraForward.y = 0;
cameraRight.y = 0;
cameraForward.Normalize();
cameraRight.Normalize();
Vector3 move = (cameraForward * moveVertical + cameraRight * moveHorizontal).normalized;
controller.Move(move * speed * Time.deltaTime);
if (move != Vector3.zero)
{
transform.forward = move;
}
if
(Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
//right here AI keeps telling me that i should add (* Vector3.up) but then i get a error if added
}
}
//code
stop talking to the AI that helped you write this code immediately! Also, use https://gdl.space to post big blocks of code
if you REALLY have to move upwards, you can do this controller.Move((velocity + Vector3.up) * Time.deltaTime);, but I'm fairly sure you don't...
Any idea what's wrong about my code?
[SerializeField] new Renderer renderer;
Texture2D originalTexture;
// Start is called before the first frame update
void Start()
{
originalTexture = (renderer.material.mainTexture as Texture2D);
int height = originalTexture.height;
int width = originalTexture.width;
float x = Random.Range(0,249092);
float y = Random.Range(0,249092);
for (int i = 0; i < width; i ++) {
for (int j = 0; j < height; j ++) {
if (originalTexture.GetPixel(i,j).a == 0) {
originalTexture.SetPixel(i,j, new Color(0,0,0,0));
}
else{
if(Mathf.PerlinNoise(x + i,y + j) < Random.Range(0.000f,1.000f)){
originalTexture.SetPixel(i,j, new Color(0,0,0,0));
}
}
}
}
renderer.material.mainTexture = originalTexture;
}
It makes unity freeze
that aside, calling controller.Move() twice on the same frame/method is a bad practice and could bring forth issues
it freezes coz you're iterating through THIS many pixels, lol.
or not, idk.. but yeah if that's the case don't do it 😛
Anyone can help me I was just working as usual and any new scripts I created dont use unity
Am I? I don't think I am
how big is your texture?
The random values are just offsets for the perlin noise
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
also, have you tried commenting out JUST THE START method here? and see whether it still freezes
529 * 472
I can run a single method on it's own?
Will try but shit just stop working out of nowhere
well 250k operations shouldn't make it freeze, but if you have, say, 100 objects that have this, it might take a long time
The part where it destroys the bullet is disabled
I have like 3
ah yeah, and sorry for answering late, my light had went out
Might be because all the objects that are running this script are editing the same texture
How can I create an instance of a texture?
Looks like it is an instance already
var pixels = originalTexture.GetPixels();
for (int i = 0; i < width; i ++) {
for (int j = 0; j < height; j ++) {
var index = i + width * j;
var x = Random.Range(0,249092f);
var y = Random.Range(0,249092f);
if (pixels[index].a == 0) { pixels[index] = Color.Clear; }
else if (Mathf.PerlinNoise(x + i, y + j) < Random.Range(0f, 1f)) { pixels[index] = Color.Clear; }
}
}
originalTexture.SetPixels(pixels);
originalTexture.Apply();
renderer.material.mainTexture = originalTexture;
Thanks!
this will be much more efficient than 250k GetPixel calls
That's much faster
But sttill no noise on my texture lol
I'll try to figure that out
@sleek gazelle check updated version for noise
It's still the same? Except you removed the .000
oh actually they have an example implementation here: https://docs.unity3d.com/ScriptReference/Mathf.PerlinNoise.html
no I made each x/y be calculated inside the inner loop
why stop talking to that AI?, and i mean this script is using the camera but the camera is locked to the players view and not visa versa
That's not exactly what I need though, I need it for randomness, I don't want the actual noise to be applied to the texture
did not help man
because it's obviously not smart enough to teach you how to code and I believe it'll teach you bad practices instead :/
That's not what I need but thanks anyway
np good luck
I found why it doesn't work:
ArgumentException: Texture2D.SetPixels: texture uses an unsupported format. (Texture 'RoadWorkSignTextureWithTransparency')
UnityEngine.Texture2D.SetPixels (System.Int32 x, System.Int32 y, System.Int32 blockWidth, System.Int32 blockHeight, UnityEngine.Color[] colors, System.Int32 miplevel) (at <2d8783c7af0442318483a199a473c55b>:0)
UnityEngine.Texture2D.SetPixels (UnityEngine.Color[] colors) (at <2d8783c7af0442318483a199a473c55b>:0)
TextureNoise.Start () (at Assets/Scripts/TextureNoise.cs:28)
Thanks!
is there that much weird? or what
the main point is the more code you write and the more complex the game gets, the harder it is to control everything if AI just wrote it all
you also barely learn anything
But I can't manage to find where the error is in the code
If I comment out the 2 conditions, it's not fixed
yeah it has some terrible practices I mentioned above. And the fact it suggests adding * Vector3.up doesn't help
var pixels = originalTexture.GetPixels();
originalTexture.SetPixels(pixels);
Why would this not work?
EDIT: texture format was wrong
the texture needs to be marked as isReadWriteable from the import settings -- is it?
what are those was what i was asking because there have been no errors in its code till that and it only puts it in sometimes, but another thing just because AI helped write some of it means get it out of the "code-beginner" channel?
Yes it is
I wasn't trying to be hostile, you misunderstood. I just genuinely think that this specific AI isn't helping you learn programming the proper way.
@stark summit maybe I'm wrong though. But yeah give it a go with the standard way of google and stackoverflow imo
using AI in general to write code for you is a bad idea, mainly you wont learn a single thing. secondarily it will lead you astray most time
This is basically just a copy of Brackeys movement code, including the mistake of two Move() calls per frame
Can you show the context instead of cropping it so much?
@grand badger just wanna say thank you! I fixed the last error and it looks super nice!
Looks like the format of the texture was wrong, so I created another texture by script with the good format (chatGPT helped me a bit in finding why it wasn't working lol), here's the code now if you want:
originalTexture = (renderer.material.mainTexture as Texture2D);
Texture2D newTexture = new Texture2D(originalTexture.width, originalTexture.height, TextureFormat.RGBA32, false);
int height = originalTexture.height;
int width = originalTexture.width;
float x = Random.Range(0,249092f);
float y = Random.Range(0,249092f);
Color[] pixels = originalTexture.GetPixels();
for (int i = 0; i < width; i ++) {
for (int j = 0; j < height; j ++) {
var index = i + width * j;
if (pixels[index].a == 0) pixels[index] = Color.clear;
else if (Mathf.PerlinNoise(x + (i * scale), y + (j * scale)) < Random.Range(0f,0.7f)) pixels[index] = Color.clear;
}
}
newTexture.SetPixels(pixels);
newTexture.Apply();
renderer.material.mainTexture = newTexture;
Is your !ide configured?
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
I don't use Visual Studio, but isn't MonoBehaviour supposed to be colored?
did you delete anything you shouldnt have?
not that im aware of my commits looks clean
Did you get it ?
guys i need help
NullReferenceException: Object reference not set to an instance of an object
MonkeyAttack.Update () (at Assets/MonkeyAttack.cs:15)
this is my error and here is the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MonkeyAttack : MonoBehaviour
{
[SerializeField] private float cooldown;
[SerializeField] private Transform firePoint;
[SerializeField] private GameObject[] bananas;
private MonkeyScript playerMovement;
private float cooldownTime = Mathf.Infinity;
private void Update()
{
if (Input.GetMouseButton(0) && cooldownTime > cooldown && playerMovement.canAttack())
Attack();
cooldownTime += Time.deltaTime;
}
private void Attack()
{
cooldownTime = 0;
bananas[FindBanana()].transform.position = firePoint.position;
bananas[FindBanana()].GetComponent<BananaThrow>().SetDirection(Mathf.Sign(transform.localScale.x));
}
private int FindBanana()
{
for (int i = 0; i < bananas.Length; i++)
{
if (!bananas[i].activeInHierarchy)
return i;
}
return 0;
}
}
!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.
do new projects work?
Can you remove this post and use the link to paste your code?
you basically deleted the file that tell files where to go to
oh i did the thing now
with the backquotes
any help would be appreciated thanks
read the bot
No, you cannot paste large code. It blocks other people's questions and answers. Use the links provided from the bot dec_ves posted . . .
nope actually
new projects dont work either
sometimes the scripts I create work fine sometimes they dont
Plus, we cannot accurately access which line the error is on as the code wraps around. Very hard to read on mobile . . .
explain what you did before this happened
it may be a bug, if it is, please follow this !bug
🪲 To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.
📝 If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click ‘Report a problem on this page’!
💡If your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.
For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting
Bro idk how to use it
click GDLspace link and paste your code
then press the save in the site
simple
paste -> click the 💾 save icon.. give us the new url thats generated
if you have everything on github already, you can try to reinstall unity
or visual studio
How would I make an object feel like it was thrown really hard?
I'm raycasting and then teleporting it to where it hits but idk how to make it feel like it was thrown there instead of teleported
(I'm trying to replicate the effect of Uzi throwing a [NULL] from murder drones)
Your ide is not configured and the issue is with the csproj file. Try clicking regenerate project files in the external tools window of unity
I was just working on my game nothing special
okay
the button doesnt do anything unless it happens in an instance
Are you clicking it when Visual Studio is closed?
yep
delete the .csproj files manually if u have to..
Try deleting all the .csproj files then do it again
the button should work tho
just to not mess up how do u do that
I’m trying to make player look in a certain direction on start. When I press start, my camera is reset to 0 and looking in the direction the mouse was last left at on the screen(ex. If mouse cursor was top left of screen on start, the first player will be looking top left when game starts).
https://gdl.space/ecusebusop.cs
https://gdl.space/osezedamig.cs
This script is attached to the camholder and Transform cameraPosition is on the player
I tried changing the player and cameras rotation from edit mode and in script, but I’m doing something wrong and need help.
any help would be appreciated
Click the files that end in ".csproj", press your delete key
That is really it
it'll rebuild them..
Sory didnt help. Same problem persist
reinstall visual studio ig (if nothing works), this problem has been going on for a while with visual studio but pretty rare
You could try a Repair via the Visual Studio Installer
Ok thanks alot. I take it as not a unity problem
Watch Untitled and millions of other Requested videos on Medal, the largest Game Clip Platform.
is there a better way of doing an enemy that shoots back
void Update()
{
if (player != null)
{
scanner.rotation = Quaternion.LookRotation(player.transform.position - scanner.position);
if (Physics.Raycast(scanner.position, scanner.forward, out hit, 15f))
{
transform.LookAt(player.transform);
if (!shooting)
{
shooting = true;
Invoke("ShootPlayer", 1);
}
}
else
{
transform.rotation = Quaternion.Euler(0, 180, 0);
}
}
}
void ShootPlayer()
{
if (player != null)
{
if (Physics.Raycast(scanner.position, scanner.forward, out hit, 15f))
{
player.GetComponent<PlayerHealth>().takeDamage(enemyDamage);
GameObject MuzzleFlashInstance = Instantiate(muzzleFlash, endOfBarrel.transform.position, endOfBarrel.transform.rotation, transform);
MuzzleFlashInstance.transform.rotation = Quaternion.Euler(0, 0, 0);
Destroy(MuzzleFlashInstance, .3f);
transform.GetComponent<ScreenShake>().TriggerShake();
redTint.SetActive(true);
Invoke("DisableTint", 1f);
}
shooting = false;
}
}
void DisableTint()
{
redTint.SetActive(false);
}
}
i would make it lag behind a bit so its not aimbot
how
i was thinking of adding spread
but its still instant
i dont know how to make actual bullets that travel
this is my 6th day of unity
i would !learn the basics of unity
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
if you know what i'd need to learn
i dont like just going through everything one after another
i prefer finding what i need then learning it and using etc
if you dont know the absolute basics of unity you should not be making a project like this
what basics
These basics
#💻┃code-beginner message
Essentials and then Junior Programmer pathways at least
I’m trying to make player look in a certain direction on start. When I press start, my camera is reset to 0 and looking in the direction the mouse was last left at on the screen(ex. If mouse cursor was top left of screen on start, the first player will be looking top left when game starts).
https://gdl.space/ecusebusop.cs
https://gdl.space/osezedamig.cs
This script is attached to the camholder and Transform cameraPosition is on the player
I tried changing the player and cameras rotation from edit mode and in script, but I’m doing something wrong and need help.
any help would be appreciated
i think it's because mouseX and mouseY is always 0 at the start
you could try setting the camera's transform.forward to the direction you want
https://docs.unity3d.com/ScriptReference/Quaternion.LookRotation.html
or this. I'm not too sure
why not set mouseX and mouseY on start
because mouseX and mouseY is a mouse input
you set mouseX to 90deg and it will start there
its not a -1 or 1 input
it adds up over time
or decreases over time
how would I do this?
it actually might be Xrotation mb
thank you for responding
i tried transform.rotation = Quaternion.Euler(0, 180, 0); on cam but that didnt work
set Yrotation on start
how would I properly set this rotation on start?
Yrotation = //something in the start method
thats what im stuck at lol
yRotation.rotation = Quaternion.Euler(0, 180, 0); and yRotation = Quaternion.Euler(0, 180, 0); wont work
no literally just do Yrotation = //something
you dont add a vector
ahhhhhh
it workeddddddddddddddd
thank youuuuuuuuuuuuuuuuuuuuuuuuuuuuu
lol idk why I kept doin 3 instead of one
so im making this world for vrchat and when i go to run it to test it out and everything. it doesnt let me move or anything. ive checked the meshes and ive even loaded it into a whole new project and still nothing
!vrchat
Join the growing VRChat community as you explore, play, and create the future of social VR! https://discord.com/invite/vrchat
I had zero clue you were talking about vrchat
you should use thier discord instead
@upper geyser still want help?
Did you read the message??
!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.
https://gdl.space/bupajokola.cs
can anyone help me this is the error i am reciving in unity this is my first time so i am not the greatest lol
NullReferenceException: Object reference not set to an instance of an object
MonkeyAttack.Update () (at Assets/MonkeyAttack.cs:15)
thanks
did you read line 15 of your code?
Stacktrace guide:
at Assets/MonkeyAttack.cs:15
| PATH | Line of code
And a guide explaining what a NullReferenceException is, and how to fix it: https://unity.huh.how/runtime-exceptions/nullreferenceexception
if i do
GameObject obj = new GameObject();
obj.AddComponent<myCustomComponent>();``` how can i change `obj` without deleting what it was before?
idrk how to explain it
If you don't want to change the value of the variable obj, then don't change it
That's really the most I can answer with the info given
i basically just want to temporarily hold an object and then let go of it without deleting it
Then like that
but im not really sure how i would do that
The code you've done will do that
will it delete the object im holding tho
Do you run any code deleting it
alright ty
{
Program program = new Program(0, "Test Message");
program.GetMethod(program.dotCount).Invoke(program.message); // just recently learned I could do things like Grabbing a Method via a string
program.CallMethod(program.dotCount, program.message); // this is more of what i'm used to
}
Action<string> GetMethod(int index)
{
switch (index % 3)
{
case 0: return A;
case 1: return B;
case 2: return C;
default: return DefaultError;
}
}
void CallMethod(int index, string message)
{
switch (index % 3)
{
case 0: A(message); break;
case 1: B(message); break;
case 2: C(message); break;
default: DefaultError(message); break;
}
}``` decisions, decisions..
Get yourself an Action<string>[] and you can get rid of the switch statement: return actions[index % actions.Length];
everytime i realize something cool, its always just the tip of the iceberg 😄
And did you check the 2 things it told you to check?
ok, so screenshot your console
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEditor.Experimental.GraphView;
using UnityEngine;
public class BallMoveMent : MonoBehaviour
{
private Rigidbody2D rb;
public float startSpeed = 100f;
public float speedIncrease = 1f;
private Vector2 currentSpeed;
private int collisionCount;
void Start()
{
rb = GetComponent<Rigidbody2D>();
StartMoveMent();
}
private void StartMoveMent()
{
float x = Random.Range(-0.5f, 1f);
float y = Random.Range(-0.5f, 1f);
Vector2 direction = new Vector2(x,y).normalized;
rb.velocity = direction * startSpeed * Time.deltaTime;
Debug.Log(direction);
currentSpeed = direction * startSpeed;
}
public void OnCollisionEnter2D(Collision2D collision)
{
collisionCount++;
if(collisionCount % 5 == 0)
{
rb.velocity *= speedIncrease;
}
}
}
``` This script was supose to give the ball a random directions on every directinos exept for straight right or straight left. but it just gives a random direction. What to google to get some type of answer? apperntly i dont know how to google
random.range is a random number between the two inputs
yes but the inputs make it so the ball goes straight sometimes. i dont want that
thats how random works?
no
there will always be a chance of it going forwards no?
i want to restrict it
then you need to clamp it
you would use Input.GetAxisRaw("Horizontal") or Input.GetAxis("Horizontal") for inputs
THIS how should i know to google clamp?
not random.range
you are right 😄 im not asking it to be controlled
He wants random uncontrolled movement it looks like. So no input at all
ah ok
its a god damn pingpong game. the ball should just start moving but it needs some restrictions. but now i want to know how i should know how to google clamp?
i see that
yeah im reading over it to see if i can think of a solution
ive never had this exact problem
can you try and explain what you want to happen, and what is happening
im gonna try to paint it 😛 but i paint liek a 2yr old give me a min 😄
ok
HOW you should know what to google? You wanted to know how to limit some values. When I googled "unity limit values" it was the first result. Sometimes just asking the question is perfect. Hope that helps for the future
why are you so agressive
green direction correct red not
im getting all of them 😄
I have seen you attack like six people today. I was trying to help them know how to google things and hopefully give them some confidence with that.
Stop attacking people
I am blocking you. I don't get why you are so hostile and angry to everyone. No one was ever hostile to you as far as I saw
ok.
how did you get from restricting direction to limit value?
well obviously you are getting a random range between X and Y which is in all directions
just get a random range between X
A direction is just values, so you can restrict those values as needed
or Y depending on how it is orientated
but then it wont ever go up?` or down
For Y choose between -1 and 1 (0 excluded) and build the direction vector from that
Make sure to normalize the vector though, that should give it a "random" Y velocity since normalizing affects both X and Y
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEditor.Experimental.GraphView;
using UnityEngine;
public class BallMoveMent : MonoBehaviour
{
private Rigidbody2D rb;
public float startSpeed = 100f;
public float speedIncrease = 1f;
private Vector2 currentSpeed;
private int collisionCount;
void Start()
{
rb = GetComponent<Rigidbody2D>();
StartMoveMent();
}
private void StartMoveMent()
{
float x = Random.Range(-0.5f, 1f);
float y = Random.Range(-1f, 1f);
Vector2 direction = new Vector2(x,y).normalized;
rb.velocity = direction * startSpeed * Time.deltaTime;
Debug.Log(direction);
currentSpeed = direction * startSpeed;
}
public void OnCollisionEnter2D(Collision2D collision)
{
collisionCount++;
if(collisionCount % 5 == 0)
{
rb.velocity *= speedIncrease;
}
}
}
``` like this? seems to be working, but i do not understand why 😛 Thanks though
you changed values in the range
Might wanna make those values variables, but that is not super important now
Like xMin, xMax, yMin, yMax
For Y it will still have a chance to return 0, although with a low probability
could do 😄
Like I said though, no biggie for now. You are just testing haha
Thanks.
im trying to make a pingponggame without using to much help 😄
Ah, then sorry hahaha. You seem like you are on the right track and doing well though from what I saw
thanks now to my issue, how could have google my way to changing the value. even though its probably just math 😛
or my next problem..... now the stupid ball stops bouncing and goes in a single direction after the bounce 😦
you need to flip the velocity when you hit a wall
So for that one, maybe something like "unity change direction after bounce" and ignore any tutorials, see if there are any docs pages that pop up
I am avoiding giving you the answer, unless you want it
Can someone help me with this, I've got a sorting algorithm where if the player is at a higher checkpoint than the other, their position moves up the list
But it's being sorted the other way, the ones with a lower position are coming first
ill save the answer for later 😄 how ever the google didnt give me any hintsd 😄
The top one has position 0 and the bottom has position 1, it should be the other way round
i would recommend flipping the velocity
thats a hint
using System.Linq;
playerObjects.Max(p => p.position.checkpointNumber);
It's running in a sorting algorithm, how would i use max here
thanks for the hint. i will check that. not totaly sure what you mean by that but but 😄 need to sleep soon
Needs to be compared between two players
Well, you just want to sort them by their numbers?
This is a global class that I use for collectible storage, changing scenes and all that (at least that's my intent), and found something weird. LoadScene works fine, but RestartScene says that Instance is not defined. I don't know how to approach this. Any ideas?
Script -> https://gdl.space/hiburisosi.cs
No, should have said sorry. It sorts by lap number first, then checkpoint, then distance to checkpoint
Aren't you supposed to use
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
oh, I didn't think of that xd
So you can make a list out of them and use OrderBy?
Are there also supposed to be other players? Since I don't see why you need a List for 2 items
Yeah, it's a network game i'm just testing with 2 clients right now
Difficult to test with more
I would use OrderBy
Okay I'll have a look ty
Do you have to perform an action on each player, regardless of them being the 1st in the order or not?
ok for this time i would like tha answer. so i can go to bed happy for once 😄 the googling did not give me anything
It runs on a managerscript that has references to each player object
Calls the sort function each frame
Really inefficient but i'm just trying to get something working right now
Does orderby still support selection like i've done above? I'd rather not call the distance function unless two are the same
I'm not sure what you want to do
You haven't answered my previous question
Sorry i'm not really sure what you mean
Describe what you want to do
It's a bubble sort algorithm,
First it checks if the otherplayers lap is lower, then it swaps if it is
If theyre the same, it does the same for the checkpoint number
If the checkpoint numbers are the same, then it checks the distance of the two players from the next checkpoint
Then if the other player is further it swaps them
after a few bounces this happends ``` using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEditor.Experimental.GraphView;
using UnityEngine;
public class BallMoveMent : MonoBehaviour
{
private Rigidbody2D rb;
public float startSpeed = 100f;
public float speedIncrease = 1f;
private Vector2 currentSpeed;
private int collisionCount;
private float bouncOffset = 0.1f;
private float minX = -0.5f;
private float minY = -1f;
private int maxX = 1;
private int maxY = -1;
void Start()
{
rb = GetComponent<Rigidbody2D>();
StartMoveMent();
}
private void StartMoveMent()
{
float x = Random.Range(minX, maxX);
float y = Random.Range(minY, maxY);
Vector2 direction = new Vector2(x,y).normalized;
rb.velocity = direction * startSpeed * Time.deltaTime;
Debug.Log(direction);
currentSpeed = direction * startSpeed;
}
public void OnCollisionEnter2D(Collision2D collision)
{
collisionCount++;
if(collisionCount % 5 == 0)
{
rb.velocity *= speedIncrease * bouncOffset;
}
}
}
You could do what sashok is saying and take the velocity and simply negate it with a - sign.
Or look up Vector2.Reflect
I dont know how advanced this is but I feel like its relativity beginner so im going to ask help in here
Im currently working on my FPS game with a lock on system similar to Metroid Prime/Dark Souls. I have made it so a raycast is shot out from the player camera and returns a vector 3 of a targetable object. After that, the player can push a button to make the camera LookAt the the targetable objects postion. However after the player is no longer holds the input required for the camera to target the object the camera goes flying off into a different direction.
{
CheckTarget();
if(inputHandler.TargetTriggered)
{
Debug.Log("Is Targeting");
transform.LookAt(TargetsPostion);
orientation.transform.LookAt(TargetsPostion);
}
}
private void CheckTarget()
{
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity, targetLayer))
{
Debug.Log("Object Hit");
TargetsPostion = hit.point;
}
}```
Below I also provided a video of my issue
oki thanks i will try that if i can understand what you mean by that 😄 but with some testing maybe 😄
Do you have to actually order all the players in the list, or get a single one?
Since I've only heard about 2 now
Yeah, as each client will want to know their position in the list
And they're all separate objects
players
.OrderBy(p => p.position.lapNumber)
.ThenBy(p => p.position.checkpointNumber);
Perfect ty
Then i just do a check for ones that are the same? and then do the distance check from before
What do you mean?
If two players both have the same next checkpoint
You have to check till the point you are sure the player's ranks are not the same
Use ThenBy as many times as you wish
The one thats the closest needs to first
OrderByDescending and ThenByDescending exist
No but i havent calculated the distance already
I only want to do it if more than one player has the same checkpoint number
Because its an expensive algorithm to call each frame
And once you get 16 players running it for each of them will wreck performance
that worked perfectly, thanks
use cs float sqrDistance = (pointA.position - pointB.position).sqrMagnitude; float sqrThreshold = distanceThreshold * distanceThreshold;
That's what ThenBy does
its cheaper but by how much idk
If OrderBy has left an Enumeable with the same values, ThenBy orders the same values once more
https://gdl.space/bupajokola.cs
can anyone help me this is the error i am reciving in unity this is my first time so i am not the greatest lol
NullReferenceException: Object reference not set to an instance of an object
MonkeyAttack.Update () (at Assets/MonkeyAttack.cs:15)
thanks
So, here
score time
200 50
400 40
200 30
Since 2nd and 3rd players have the same score, it's going to call ThenByDescending on time, and give
score time
400 40
200 30
200 50
Okay ty thats a lot easier
One of the objects on line 15 of MonkeyAttack.cs is null/unset/uninitialized. Probably playerMovement?
But I thought that I initialized playerMovment as monkey script which is my movement code and ground check
Sorry, I'm super new to Unity (just got here), but lots of experience in C#. Maybe the answer is obvious to someone else, but I don't see anywhere in your script where you set playerMovement = anything
That is just declaration, not initialization
Oh I didn’t know that lol
You only told what type it is and its name, but didnt assign a value
So I just gotta write
playerMovement = some value
i want that lizardman kills pigman but pigman dont want to die can someone help me
Yeah or assign it in the inspector
Ok well I will just assign it to 0 cuz I don’t want it to be moving while attacking thanks and also thanks @steel mauve
can you help me execute a pig
Show the code of course
wich
As seen in #📖┃code-of-conduct , do not ping people that are not in a conversation with you already
The one that is supposed to do what you want
ofcourse not
Troll detected
im not
If you cannot show what you need help with, we cannot help you of course
you still havent explained the problem
what is pigman, we have no idea what you're doing
Nothing here even has anything to do with attacking
sometimes we both fly away
It just animates and scales
that doesnt explain what this represents in your game?
Wow, that's epic
yes you said that
but the pig wont die
bu you havent explained the mechanics of the game..
ok slowly getting somewhere useful..
maybe create a complete paragraph and explain the problem further..
did you put a script on it ?
put the collider , set it to Trigger. Use OnTriggerEnter to inflict damage on the Pigs health script
health script?
yea do you know what a script is?
so whats the confusion, create a health script
You create yet another script
oh my
yes if you want to make anything useful , you will need scripts..lots of them..
its fairly simple setup, use a Trigger on one script and health on the other. They both interact
you just cant put the script on a disabled object or it wont work
Could you also tell me, who wins: pigman or lizardman?
manbearpig
Yeah, that's some epic shit
right
needs some screenshake goodness
oh hell yeaaa
i cant tell if you mean its cool or its actually not 😂
im getting mixed signals
iTS FUCKIN AWESOME DUDE
you dont even know where ill go with this shit
it will not be a fighting game
it will be a whole show
The only thing left is to improve pigman's fighting spirit
yap
stands there like a pig
i need blood splattering across the black wall
aswell
Hi this is the first time ive used a switch inside a for loop, im trying to get the amount of items inside a list and put those values into specific array indexes; i always remains a 0, the console says IndexOutOfRangeException: Index was outside the bounds of the array. test.Update () (at Assets/test.cs:20)and the Debug.Log in the switch statements never gets called.
List.Count is one more than the maximum index of a list/array, which is why you're probably getting that exception
oh my gosh i just rezlied the ammoun of coppy paste errors
public int[] AmmountsInTheLists = {0,0,0,};```
```cs
public int[] AmmountsInTheLists = new int[3]```
Make sure that, in the Inspector, your array has 3 items all set to 0. Since AmmountsInTheLists is marked public, the Inspector will serialize it and potentially overwrite what you've set in the code.
that fixed it thankyou
The rest of the code looks fine regarding the loop and the array accesses with i
To avoid the issue in the future always set the upper bound of the loop to the array's length, so it adapts when you resize it. for (int i = 0; i < AmmountsInTheLists.Length; i++)
i always like to debug my results before everytime i access them for things like this..
.Count atleast
yeah i kinda rushed making an isolated script of the section of code that was causing my issues
Utils.cs
public static float OptimizedDistance(Vector3 a, Vector3 b)
{
return (a - b).sqrMagnitude;
}
public static bool InRange(Vector3 a, Vector3 b, float range)
{
float squaredRange = range * range;
return OptimizedDistance(a, b) < squaredRange;
}
```useless or nifty?
yo i got the health and the weapon got melee damage but pigman dont want to feel it
i dont know
Dbug and find out why
show the setup
how can u hop in a call
- Health Exists and has Value
- Weapon Exists and has Value
- Weapon/Holder interacts w/ pigman
- Value calculates w/ Value
- End Value is Presented
no. just show which script you created, and which object you put them on
screenshot is is ok for inspector. Send code via links
mate I dont need to see the sprite
AHAHAHA
i get it
his attempt at meme'ing
frustrated bro
<<too old to understand Z yuth memes :\
im 25
yea, i think its included free of charge in any type of Coding
With the processing power we have nowadays, I'd say not doing a square root will have a very negligible impact on performance. If you're calling this method 10k times a second sure you might see a difference! And you'd also have added the aggressive-inlining attribute on top of those methods to tell the compiler to pull the code up directly to the calling method (to avoid an expensive (?) virtual call)! Or used Burst or Jobs already, idk
anyway.. its easy.. like i said Debug the values.. every step of the way
once ur debug returns something u dont expect.. u found the issue
no, id thinkso.. so far its just got XML tags
That is gen z
1997 to 2012 is commonly used for it
todays my Discovery day.. I like to start with a few stretches... and then work my way up to using System.Reflection;
i do distance checks primarily for (in range) type stuff... soo thats the method out of hte 2 i'd use more often..
i dont need to know if its squared or not. but only if its within my range variable
i might keep it just for hoots
id just rename it to SqrDistance rather than optimized, because its not really clear just from the name.
solid idea.. ty
Keep in mind the aggressive-inline attribute is more of a suggestion to the compiler, and it can just ignore what you want, and can even end up making the function call slower 
float squaredRange = range * range;
return DistanceSqrd(a, b) < squaredRange;```
You technically could use extension methods to do stuff like this?
bool inRange = (vec1, vec2).DistanceLessThan(5);
I hate it, what is going on with my brain right now
thats kinda what i was trying to do but i build em out independently in my static Utils class first for some reason
thats soo pretty 😍 lol
i try to think like cs bool inRange = (vec1, vec2).DistanceLessThan(5); this while im writing.. so I know the final use-case will look good and be readible + simple alll of that jazz
but its harder to do in practice (for me atleast)
Could do the Godot approach where they english most of their API
var inRange = vec1.DistanceTo(vec2) < 5;
i think spr2's code is actually more friendly
I like how Godot's read like plain English when you say the words out loud
i'd not know how to do yours or theirs tbh now that i look at it
dont understand how u can just tack on a DistanceTo() function to a float
public static float DistanceTo(this Vector3 from, Vector3 to) {
return (to - from).magnitude;
}
(╯°□°)╯︵ ┻━┻
u make it look so simple
I’m just gonna reply to my issue up here cause it got buried in the chat, if anyone got any advice or wisdom they can share please do!
i can add this anywhere right?
Has to be in a static class
doesn't have to be in the float class or w/e or named Float
ya ofc
In a static class, and then it's accessible project-wide
i been stacking everything in a Utils.cs
probably time to stop doing that
For mine:
public static bool DistanceLessThan(this (Vector3 a, Vector3 b) pair, float distance)
{
return (pair.b - pair.a).magnitude < distance;
}
cursed tuple
Yeah that's why I don't like it lol, it abuses tuples
public static bool DistanceLessThan(this (Vector3 a, Vector3 b) pair, float distance) => (pair.b - pair.a).magnitude < distance;
``` dis possible?
Sure!
i still keep going back to this.. its kinda shocking.. (its hard for me to read lines like this b/c i cant conceptualize how they're build)
soo thanks for the context @zenith cypress @short hazel
You should separate your utility/extensions into classes like: BoolUtils, VectorUtils, MathUtils, etc . . .
i totally agree.. was just jotting something like that down actually 😅
edit: on the priority todo list
I started making ridiculous extensions just cuz. cs if (intVariable.IsLessThan(5)) { }
if (isReloading.IsFalse()) { }```
The C# dev team actually works on better extensions right now, it won't be in the next .NET release but they did a few demos, where you can add new members (including properties!) to existing types, looks like this:
public extension SampleEx for string
{
// length of the string, squared, because why not?
public int LengthSquared => Length * Length;
}
// Usage
string s = "ab";
int ls = s.LengthSquared; // -> 4 | Seamless integration
I guess one that would be useful-ish for Unity is something like this:
transform.position.Log("label")
"debug, execution is here".Log();
Implementation exercise left to the reader...
I'm still super uneasy about them, might be good, but also might be more confusing for onboarding when they see new properties mixed with existing one where they can be on instances and/or static. Guess we will see what it ends up doing to codebases in general when it comes out lol. Wonder if unity will be using modern net by then 
holy crap, it took me this long to realize how extension methods really work.. and the whole this implication 🫣
if theres a way, i'll eventually get around to procrastinating enough to find it
bruh.. i feel like not know that stuff has been a reeal hinderance on my learning/progressing lmao
Yeah the "is this built-in or from an extension?" side of it is what scares me a bit
I guess if the IDE has a way to differentiate them (different color or font style, special icon in the completion list) it's fine, but for the 3 users who don't use an IDE, or do code review on GitHub for example it might get really confusing
i feel like i just took a big step backwards
(but got gifted a brand new pair of boots i guess)
Just don't overuse it 
i wont..
lol
i used chatgpt to explain the this keyword a little more thoroughly and it was just complaining about tuples and how that original method wouldnt work
Once extensions go live on Unity I will finally be able to implement transform.back, .down, and .left muahahaha
(v, v2).DistanceLessThan(5);
heh, i have a .North and all the Cardinal Directions lol
well, an enum and switch statement actually
it stays zipped up in the regions
b/c its hideous and i feel bad
I can't wait for readonly record structs (great for a chunk of ecs component definitions), SIMD/compiler instruction access outside of Vector types, file-scoped namespaces, etc 
We go wild when there's no activity
Maybe there are 50 people reading and asking themselves "if this is beginner code i am not ready to participate here"
- extension methods not cause any extra taxing on the ide/compiler? (b/c of hte multiple ways they can be written) nvm.. i dont think so nvm
- are Tuples okay to use like that on extension methods? (v, v2).DistanceTo(10);
I wouldn't worry about performance on extension methods.
im not in general.. just curious more
- Nope, it's compiler tomfoolery like most "modern" things. Compiler just replaces your code with a standard call to the static method (hence why both the class and method must be static)
- Tuples are types like any other
roger that 🫡
SPR2 gots it.
Basically:```cs
"something".Extension();
// ->
MyExtensions.Extension("something");
ahh, yea i get u now..
in the end its all gonna be what is gonna be
well mark down another strike against chatgpt.. (quite a few now)
tellin me i cant use tuples like that.
Learn from documentation and your own critical thinking. ChatGPT is worse than a crutch for programmers.
I've only found gpt good for two things, vim commands, and converting rust structs to JS versions for Tauri 
I just made those myself. It's crazy they don't have them . . .
I love ChatGPT for documentation. It writes all my extension method summaries . . .
ya, im past the beginner stage for quite a bit now.. i use chatgpt for grunt work.. documentation writing and stuff..
but i can say its useful just as u said earlier.. combine it w/ critical thinking and it can still expose u to concepts, ideas, and whatnot pretty efficiently..
like the tuple thing seemd off, asked here to clarify, got expected answer.. sent a few pointless insult its way and now im off to the next todo bullet lol
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
so i was learning raycast
lmao same
rough stuff, but i think ive gotten it down
i was wondering "how do i cause a change to whatever its interacting with, and not everything with the layer the raycast is looking for?"
but i've notice my codeium plug-in is pretty good on its own.. filling them in after i write the method signature
like if i had a bunch of stuff on the "rock" layer or something but i had a really specific rock i wanted the player to fuck with, how would i do that?
as an example, lets say i want it to make the specific object its interacting with a child of... some other object?
actually thats perfect
when u hit something w/ a raycast u can store that object..
the layer would just be a conditional before hand to narrow down the raycast results
im not entirely sure how id do that
so the layer wont be a problem, right?
void Update()
{
ray = new Ray(cam.transform.position,cam.transform.forward);
if(Physics.Raycast(ray, out RaycastHit hit,distance, mask))
{
if(hit.collider.transform.TryGetComponent(out IInteractable interactable))
{
cachedInteractable = hit.collider.gameObject;
if(Input.GetKeyDown(interactKey))
{
interactable.Interact();
Dbug.Italic($"Interacted with {cachedInteractable.name}");
}
}```
do i just go "gameobject", and then shove whatever game object fits that role in there
soo. here its not the exact same.. but u can see where i got the hit.collider.transform
out RaycastHit hit this part here stores it for me when the raycast has a true-hit
okay so id be looking for it hitting the mask, and then hitting object collider, and then trying for it to get whatever applicable script for "Interactable?"
// we somehow got a hit
// var theThingYouHit = hit.gameObject;
}```
it seems more study of raycasts is needed
the mask is within the raycast method.. u dont even have to worry about that..
- after it hits something (that means its in the mask)
- then do another check to see what it is (if u want to interact w/ it)
- now store the gameObject
see store is where you're getting me
ray = new Ray(cam.transform.position,cam.transform.forward);
if(Physics.Raycast(ray, out RaycastHit hit,distance, mask))
{
//this will only be objects w/ layers that are in the mask
}
thats why i also linked an article
thank you
White cubes are original navmesh path corners. Black cubes are the path corners translated to the grid. Green line is for visualizing a straight path or not. Why is it that the navmesh insists on creating two intermediary corners when there is a perfrectly straight line from start to end?
Edit: hmmm. It's tempting to just give it a metric ton of information and just, remove any redundant nodes
If I change the string variable in InvokeRepeating to the name of another function while its running does it change which function it calls?
nah, invoke repeating starts and then continues to call the same method until its canceled
Or the invoking object is destroyed or PERHAPS disabled?
What about a normal invoke? If that invoke repeats in updates for example and its value is changed will that work?
no
Sorry. I see what you mean. The NEXT time it is called, yes
Generally just don't want to use invoke or invoke repeating. A delegate may be better (without knowing the use case)
Oh ok good. I just need a way to call functions from a string with their name.
why
Enemy ai brain. When the ai is doing a certain action then it sets the string to the function that corresponds with that action.
why are you using strings at all for that
this line of code stopped working for no reason, even though I didn't do anything in this script
if(Input.GetKeyDown(KeyCode.Alpha1))
is that line perhaps inside of FixedUpdate?
nope, just update
are you certain the code is actually running?
it used to work fine, but when i added something in unity, it stopped working
yes
Well what did you add
be less abstract. nobody can possibly guess what you've done that made it stop working unless you provide actual details
Did you enable the new input system?
quick way to set which function needs to be called. Like when it stands for a certain time so the standing function decides to walk and so it sets the function that is called each 0.1f seconds to the one that corresponds to walking. Having it be strings means I can call it by name and not need a big switch statement.
i assigned an unrelated script to an unrelated object
That will not affect the ability to read input
this is still not a reason to use strings. if you're manually typing the strings in anyway, you can also just type the method name for an Action or even just call the method properly
that's why i'm asking why it stopped working
Send over the script to see if it is a logic error. Also put a debug log before the if statement to see if the script is even running properly.
because it was always flawed from the beginning and this random vague change you made isnt related
How have you discerned it "stopped working"
what have you done in order to demonstrate that
i put a debug log before it, and it worked, also lemme send the script rq
Also, you are pressing Alpha1 right? 1 on your top row of the keyboard (not numpad 1).
it used to do what was in the if statement, but now it doesn't, even when i added a debug log
yes
Just making sure 👍
Did you press numlock
no
try it
Ah wait, alpha1, that's the normal number, nevermind
Continue with posting the !code then
📃 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.
doesn't work
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gun : MonoBehaviour
{
public GameObject bulletPrefab;
public GameObject gun;
public GameObject player;
private string weapon_active = "None";
private Renderer rend;
private GameObject bullet;
public GameObject camera;
public Vector3 mouse_pos;
public bool bullet_move = false;
void Start()
{
rend = GetComponent<Renderer>();
rend.enabled = false;
}
void Update()
{
if(Camera.cursor_locked)
{
if(Input.GetKeyDown(KeyCode.Alpha1))
{
Debug.Log("works");
if (weapon_active == "Gun")
{
rend.enabled = false;
weapon_active = "None";
}
else
{
rend.enabled = true;
weapon_active = "Gun";
}
}
if (weapon_active == "Gun" && Input.GetMouseButtonDown(0) == true)
{
GameObject bullet = Instantiate(bulletPrefab, player.transform.position, camera.transform.rotation);
Bullet bulletScript = bullet.GetComponent(typeof(Bullet)) as Bullet;
bulletScript.direction = player.transform.forward;
bullet_move = true;
}
}
}
}
Okay, so, it's never printing "works". Put a log before that if, but still inside the Camera.cursor_locked one. Does that log every frame?
yes
i already tried it
Put a log there, then show a screenshot of your console after you tried to hit the button
put a log before the if statement?
Before the alpha1 if statement, yes
ok one sec
Yes, before the input statement, after the cursor statement
Ok actions is a pretty decent suggestion but I'll see if this works first
Okay, no errors. Try enabling "Collapse" so you'll be able to see if there's anything in there
Okay, so, it would seem that Alpha1 is never pressed on a frame this object is active for. Try changing it to a different key for testing
Also make a new Mono script and see if it works there. Just put the script on some random object in the scene
any key or another number?
Any key. Let's say Spacebar
still doesn't work
i pressed space like 30 times
it doesn't say works
Okay, show a screenshot of the inspector of this object while your game is running
wdym
play game, pick up weapon, show weapon in inspector
Take a screenshot of the inspector of this object while your game is running
At a time you'd be expecting the button to work
wait
i remembered that my jump button is space
lemme try a different button rq
no buttons work
i can't move or jump, i can only look around
hello?
Camera.cursor_locked is probably the issue
why
is anything being called underneath it?
also should avoid using a class named Camera
yes, the if statement
no i mean did you test it
Have you tried restarting Unity
i haven't saved, should i save and restart unity, or should i try to fix it, and if it doesn't work, restart it without saving (and lose some progress)
Save and restart
ok, it might take a bit to re-open because my pc is bad
yes
allz i saw was every frame
did you place a debug right underneath the Camera.cursor_locked and not in any if statements?
yes, and it worked
my 16 gigs of ram are suffering while re-opening unity xd
i re-opened unity and it worked, thanks, but any idea why it stopped working?
hello! (top down 2d, just vampire survivors lel) I have a gun that shoots. I want that, when shooting a box, this box shoots out another bullet (just a different game object) in the same direction that it got hit. I know how to do it so it instantiates the 2nd bullet, but i have no idea how to make the second bullet have the first bullets rotation
¯_(ツ)_/¯
But if something is weird, a restart is always worth trying
When it collides, grab the first bullets transform and read its rotation 🤷♂️
other.transform.rotation
and my code that i was implementing worked first try, i'm so happy rn
Are you using OnTriggerEnter or OnCollisionEnter? Or something else
oh u can check the object that sth is colliding with?
Hello people, I have been trying to retrieve a curve attached to the current animation that is playing using this -
rotationCurve = AnimationUtility.GetEditorCurve(_psm.playerAnimationManager.animator.GetCurrentAnimatorClipInfo(0)[0].clip, EditorCurveBinding.FloatCurve(path, typeof(Transform), "Rotation Y"));
I have made sure that "Rotation Y" curve is present and also the name is returned properly. It still returns NULL, Could it be the binding?
Well yeah of course. Collisions would be near useless if not
How are you even detecting the collision? I can tell you more if I know
OnTriggerEnter2d
Then that gives you the collider of the other object
OnTriggerEnter2D(Collider2D other)
{
other.transform.rotation
}
That will be the bullet if the script is on the cube
why doesnt this work
!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.
please
sorry
Describe "doesn't work"
Because that is not actionable
use a bin site
oh thank you! :D
whats a bin site
Missing curly brace perhaps
Likely an unconfigured !ide
watch
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
btw how do i make it so that it fullscreens when i playtest (i used to have it but i restarted and i forgot how to do it)
go to game view and at the top it should say fullscreen, focused, unfocused
right to the left of the play button
if(flatVel.magnitude > moveSpeed)
would this need ;
show the code
didnt fix it
im using notepad
for an IDE?
don't
get visual studio
it only says, play maximized, play focused, and play unfocused, and when i when i choose play maximized and playtest again, it doesn't save my choice
whats wrong with notepad
you need to not be in the game when you select it
Everything
was the game running when you selected fullscreen?
It in fact needs to NOT have a semicolon. That would break the if statement from the body
im not missing a ; i dont think
Look under the other/none link in the bot
#💻┃code-beginner message
ive been looking at this for a good 30 mins
yes, and when i tried without the game running, it fullcreened while i wasn't in the playtest
Show.... the code
Load the code in any IDE and it'll be underlined in red
thats why, you need to select it while not in the game
Don't use notepad
fine
nothing saves while in game
but i dont see whats wrong with note pad
it does nothing good for you
its just notepad
It does literally nothing
it works
you are on extreme difficulty
You might as well be writing your code on a piece of paper
for programming
now that would be different
its working i got wasd to work and the cam
You will not end up with a working program either way
dude get an ide
i am
the purple one
visual studio?
yea
Literally everything. There js nothing GOOD about using notepad with unity or coding.
In fact it is a rule that we cannot help you without a configured ide, and notepad is not an ide
Ah, lag
its installing rn
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Now open it and see where the red underline is (as long as it is completely configured)
Continue following the guid for configuring your IDE, then see where your error is
what are you confused about?
well you need to open a script
how
via unity or from Visual studio
hold up
Same way you opened it before
If you followed the guide, it will now open in vs
like the one in notepad
double click a script in unity
Then you did not follow the guide completely
got it
add another }
at the end of your script
dang man i thought it would have been a ;
bummer
You have a semicolon after an if statement on line 74. As we said, never do that
But yes, this is not configured. You still did not do the guide
Are you sure? There is the if, method, and one extra which is likely the class semicolon there
If all of these are in a namespace, then yeah it needs another
well other than the semicolon but the error said line 81 space 1
and you can see the dotted line that should be there
connecting the script
but it isnt there
Ahhh, I see it. It is a missing PARENTHESIS on line 77
muahaha
That is line 77
As I said
It is COLUMN 71
It is the exact error I described
#💻┃code-beginner message
didnt fix it
It will if you did it right
put a } at the end of the script as well
Put it before immediately before semicolon
unless im reading this error wrong
There is definitely not a missing curly brace
its the ; at the end of the if conditional ()
There is a BACKWARDS curly brace though
Already removed that
ahh okie 👍
i added the } at the end already
The two errors are backwards curly on line 70 and missing parenthesis on line 77
Remove the extra curly at the end that is not it, and that will cause an extra error
ok
All of this would be easy to see if you just finished configuring your ide
And honestly, we need to stop helping until you do so
id rather use notepad

