#💻┃code-beginner

1 messages · Page 499 of 1

sand snow
#

only if im not holding shift though right?

modest dust
#

GetKeyDown detects the moment a key gets first pressed

#

You want GetKey for continuous detection

sand snow
#

ohhh okay thank you

modest dust
#

But keep in mind that with your current code you'll get a massive speed boost in a matter of a few frames

sand snow
#

yeah that just happened, and it just keeps multiplying until infinity

modest dust
#

If it's a one-time speed boost only then consider either getting rid of *= and just define a constant sprintSpeed somewhere in your code and assign it rather than multiply it or look into GetKeyDown and GetKeyUp

languid spire
#

you want GetGey, not GetKeyDown

sand snow
sand snow
modest dust
#

Basically:

if (shouldSprint)
   currentSpeed = some_sprint_speed;
else
   currentSpeed = some_normal_speed;
modest dust
sand snow
#

oh I see

modest dust
#

So, once again, I suggest taking a C# course, because you seem to be lacking some basics and these are the root of your issues

sand snow
#

are the ones on Unity good?

#

like the unity learn website

modest dust
#

Take a pure C# course first

#

There's a link in the pinned messages in this channel

sand snow
#

is it free?

modest dust
#

Under Resources, Beginner, Intro to C#

#

All the pinned resources are free as far as I'm aware

sand snow
#

oh okay thank you so much 🙏

#

and by the way my sprint now works!

sand snow
#

okay i ran into another problem...

#
if (rb.velocity.x >= 0f)
{
    facingRight = true;
}
else
{
    facingRight = false;
}
#

i am trying to make a bool to see of I am facing left or right, which kinda of works

#

but if i click the left movemnt button it does say im facing left but then when i let go it reverts to facing right

#

i want it to keep looking left unless i press the right movement key again

#

i am trying to make a wall check once i make the bool so that if i am running into a wall my velocity on the x axis can no longer go that direction

#

is it not working because i am using velocity instead of something else

queen adder
#

Velocity tells you how fast is the rigidbody in the World Direction. You should choose which direction will be considered as Right. For example, local right (transform.right)? World right (Vector3.right)?

sand snow
#

ohhh okay i will try that right now i didnt know that was possible

#

this doesnt work either though, its saying "cannot implicitly convert type 'unityengine.vector3' to bool"

if (transform.right)
{
    facingRight = true;
}
else
{
    facingRight = false;
}
#

my game is 2D i forgot to mention if that matters at all

queen adder
sand snow
#

oh then cant i use Input.GetAxisRaw("Horizontal") for that?

queen adder
queen adder
sand snow
#

i accidentally click f10 while scripting and it did something

queen adder
#

But if you do that:
if (1 < 3)
Then it will be valid.
That means:
if (Input.GetAxisRaw("Horizontal") < 3)

sand snow
turbid robin
#

i have this button, even if i click it nothing happens
the code is:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class SceneManagerScript : MonoBehaviour
{
    public void LoadScene(string SceneName)
    {
        SceneManager.LoadScene(SceneName);
    }
}```
#

the onlick event seems right to me

#

also the build settings

sand snow
#

@queen adder i was able to solve my problem

#

i made a string variable "lastDirection" and used GetKeyDown to determine if my "facingRight" bool is true or false

#

so if my velocity.x was equal to 0 (meaning im pressing nothing) that my bool = lastDirection =="right"

#

heres the code:

private string lastDirection;

void Start()
{
    lastDirection = "right";
}

void Update()
{
 if (Input.GetKeyDown(KeyCode.D))
 {
     facingRight = true;
     lastDirection = "right";
 }
 else if (Input.GetKeyDown(KeyCode.A))
 {
     facingRight = false;
     lastDirection = "left";
 }
 else
 {
     if (rb.velocity.x == 0)
     {
         facingRight = lastDirection == "right";
     }
 }
}
jovial bone
#

i have a question: is there a better way to generate Random.InUnitSphere or OnUnitSphere within a parallel.for or parallel.foreach loop

#

because they usually return that they can only be run on the main thread

night raptor
ruby python
#

Okay I think I'm making progress on this rock spawning thing.

https://hastebin.com/share/irolitiyop.java

Everything is working fine, except that my height check is kinda messed up and I don't understand why.

In the code, maxYPosition is set to 3, and minYPosition is set to 1, so I'm not really understanding why my rocks are spawning below 0 on the y. 😕

Can anyone see my mistake please? Been staring at it for too long. lol.

night raptor
#

You could code the normalization by yourself and when length = 0, return (0,0,1) (almost inpossible to happen so shouldn't affect the overall distribution) or pick new coordinate. Unitys normalize method returns Vector3.zero for zero length inputs which might cause issues depending on your case

jovial bone
#

ive been working on this fluid simulation, looking at the papers i applied the equations, but when two particles got in the same position they combined so i needed a random pressure force to push them away

#

instead of just returning zero

night valve
#

Strange that unity does not provide build in SpherePoint struct for operating on polar coords, they can be really handy. Or does it? Anyways making such struct yourself is quite easy

ruby python
# jovial bone ive been working on this fluid simulation, looking at the papers i applied the e...

This may be of help (probably already seen it, but still. :))

https://www.youtube.com/watch?v=rSKMYc1CQHE

Let's try to convince a bunch of particles to behave (at least somewhat) like water.
Written in C# and HLSL, and running inside the Unity engine.

Source code:
https://github.com/SebLague/Fluid-Sim

If you'd like to support me in creating more videos like this, you can do so here:
https://www.patreon.com/SebastianLague
https://ko-fi.com/sebastia...

▶ Play video
sand snow
#

I am making a script to flip my character depending on which direction im facing, I have a working system to check which direction im walking, but my player only flips if I click A instead of A and D, if i click D my player doesnt flip but just moves with the player facing whatever way A set it to can someone please help

night valve
#

you need to provide code for someone to help you

sand snow
#
     if (Input.GetKeyDown(KeyCode.D))
     {
         facingRight = true;
         lastDirection = "right";
         Flip();
     }
     else if (Input.GetKeyDown(KeyCode.A))
     {
         facingRight = false;
         lastDirection = "left";
         Flip();
     }
     else
     {
         if (rb.velocity.x == 0)
         {
             facingRight = lastDirection == "right";
         }
     }
 }
 
 private void Flip()
 {
     if (facingRight)
     {
         transform.localScale = new Vector2(transform.localScale.x, transform.localScale.y);
     }
     else if (facingRight == false)
     {
         {
             transform.localScale = new Vector2(-transform.localScale.x, transform.localScale.y);
         }
     }

 }
 
 }
#

there is the code, sorry

#

there are 0 warnings and 0 messages, so the code is technically correct, but my player doesnt flip when I click D

night valve
#

also you can try swapping A with D behavior and see in the inspector if scale is set to negative, didnt do much 2D, but negative scale can mess things up in 3D, so maybe 🤷

ruby python
#

Sorry my answer was all over the place. lol. Gimme a sec.

sand snow
#

well i kinda fixed it so now it flips if i click A or D, but I still have same problem but both keys do it now

ruby python
# sand snow well i kinda fixed it so now it flips if i click A or D, but I still have same p...

You should be able to modify this to fit. I use this snippet to switch between firing left gun and right gun.

if (leftLastFired == true)
            {
                Instantiate(bulletPink, firingPointRight.position, firingPointRight.rotation);
                StartCoroutine(MuzzleFlashLight(leftLastFired));
                leftLastFired = false;
            }
            else
            {
                Instantiate(bulletPink, firingPointLeft.position, firingPointLeft.rotation);
                StartCoroutine(MuzzleFlashLight(leftLastFired));
                leftLastFired = true;
            }
#

Not sure how it works with 2d though tbh.

sand snow
#

I already tried changing it to work with the "lastDirection" string, it still does the same thing

#

do you thinkit would work if I do something like this:
if(rb.velocity.x > 0)
{
Flip()
}

night valve
#

then it will Flip() every frame if there is any velocity

#

if it is in update()

sand snow
#

i just tested it it doesnt do that but I still have the same problem

ruby python
#

Debug your bool and your localscale.x (or serialize them)

night valve
#

also your Flip() method is named improperly i think. Flip is to... well flip. No matter which direction. So it should be just

void Flip(){

             transform.localScale = new Vector2(-transform.localScale.x, transform.localScale.y);
}
sand snow
#

thats how it is

ruby python
#

Actually yeah, that above will just invert the current local scale, so you don't even need the bool.

sand snow
#

but if there is no bool, then how will it know which direction I am facing

night valve
#

do it outside the flip, check if direction changed, if it changed - do Flip(), otherwise dont

sand snow
#

im about to test it with out the private void, is that what you mean?

night valve
#

it doesnt matter

sand snow
#

yeah I just tested it, I thought this would happen, but my player now flips over and over no matter what

night valve
#

what i mean is:

string lastDirection = "right";
void Update()
{
  string newDirection;
  if(Input.GetKeyDown(KeyCode.A){ newDirection = "left";}
  else if(Input.GetKeyDown(KeyCode.D){ newDirection = "right";
  }
  else {newDirection = lastDirection;}
  if(newDirection != lastDirection) {Flip();}
  lastDirection = newDirection;

}


void Flip(){

             transform.localScale = new Vector2(-transform.localScale.x, transform.localScale.y);
}


#

probably it could be done better, but at least it is readable imo

sand snow
#

let me try it

night valve
#

(#edit - added semicolons)

sand snow
#

nothing happens

#

yeah nothing happens, i even copy pasted it

night valve
#

Add debug logs to print new direction and last direction when the key is pressed

#

Also debug.log "flipping" in flip method, basically debug log is your friend when anything does not work as expected

#

Also you can get rid of else statement, and set string string newDirection = lastDirection on the first line of Update, but this will probably not change anything, just make code cleaner

sand snow
#

im gonna try to find a youtube tut

#

even though i hate yt

formal sable
#

Where can I ask about colliders?

night valve
ivory bobcat
ivory bobcat
#

Ah replied to the wrong post.

night valve
#

@sand snow

sand snow
#

i found a different solution following this yt vid if you want to check it out https://www.youtube.com/watch?v=Cr-j7EoM8bg

Hi everyone! 🙂 Today I will show how to flip your 2D character in Unity.

Learn C# here: https://www.youtube.com/watch?v=HB1aPYPPJ24&list=PL0eyrZgxdwhxD9HhtpuZV22KxEJAZ55X-&ab_channel=DaniKrossing
Download Unity here: https://unity3d.com/get-unity/download

➤ TIMESTAMPS

00:00:00 - Intro
00:01:01 - My player script so far
00:01:48 - Method 1: Fl...

▶ Play video
#

go to 3:40 to see the method

#

the problem with my code before, is that the bool wasnt being used to detect if I was actually fdacing left or right, therefore I could flip infinitely

#

also im sorry if I am not allowed to put links

#

is that allowed?

verbal dome
#

@sand snow i can see 5 hours of questions from you. Maybe make a thread

sand snow
#

i got the solution

#

sorry about that ill try to start remembering, please forgive me if I forget

lapis frigate
#

umm any1 can give me a direction to how do I create a level system for an rpg game?

eager spindle
#

do you have any plans on what your levelling system is like?

lapis frigate
#

1v1 turn based combat system

eager spindle
#

What will the player do to level up?
What will the player gain from levelling up?
What will be displayed when the player levels up?

#

Do think of more questions you can break down before making this

lapis frigate
#

What will the player do to level up? defeat enemies
What will the player gain from levelling up? his stats like dmg, defence, health ect will level up
What will be displayed when the player levels up? just like standard level up messege with maybe some infomation on what happened

#

I mean I'm not looking for something too complicated just like asking if I need a seperate maneger for it or do I need to do it in the players script

eager spindle
#

Ohh

#

Make a seperate manager

lapis frigate
#

ok and what do I do there? do I not put any information about the levels in the player's script?

#

for example the current exp max exp level ect?

eager spindle
#

To be honest it's up to you

lapis frigate
#

ye ik but like im just asking for the better way to do it

eager spindle
#

But I prefer to have one responsibility per class, like player combat and player movement has its own scripts

true oriole
#

im tryna enable the moving speed under my script

eager spindle
#

So ideally you keep your RPG levelling in it's own script too

lapis frigate
#

ok tnx

stiff fjord
eager spindle
true oriole
night valve
eternal falconBOT
eager spindle
stiff fjord
eager spindle
quick spear
#

can someone help me out here, the enemy ai movement is with navmesh. Why when it start to attack the player, the circle goes past the player circle

true oriole
#

whats the issue with the code???

verbal dome
#

In addition to your error, you should not multiply mouse input with deltatime

timid ember
#

Here is a code

[SerializeField]TextMeshProGUI textdisplay
public void buttontap()
{
if (val== "=")
{
   double e=System.Data.Convert.ToDouble(System.Data.DataTable().Compute(CurInput,"");
   CurInput += val;
   textdisplay = CurInput;

}
}
public void Update()
{
public string CurInput="";
string val="4+15+63";
}

and when i press the button, it displays CurInput as NULL string, not updating itself. Although, it is updated when i press twice, but the error is still displayed:- "Cannot assign double values to DBNull"

verbal dome
timid ember
#

its all under a class

willow scroll
timid ember
#

in original code, I am using length function to CurInput

#
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Data.Common;
using System.Data;
using UnityEngine;
using TMPro;
using UnityEngine.UI;

namespace TheProj
{
    public class Clac : MonoBehaviour
    {
        public TextMeshProUGUI disptext;
        private string CurInput="";
        private double answer;

        public void ButtonTap(string val)
        {
            if(val== "=")
            {
                ans();
            }
            else if(val== "C")
            {
                Clear();
            }
            else
            {
                int s=CurInput.Length;
                Debug.Log(s);
                CurInput += val;
                Debug.Log(CurInput);
                UpdateDisplay();
            }
        }

    public void ans()
        {
                answer = System.Convert.ToDouble(new DataTable().Compute(CurInput, ""));
                CurInput = answer.ToString();
        }

        public void Clear()
        {
            CurInput="";
            answer=0.0;
            UpdateDisplay();
        }
        public void UpdateDisplay()
        {
            disptext.text = CurInput;
        }
    }
}
stiff fjord
#

is tghis the best way i could do this?

willow scroll
timid ember
#

!code

eternal falconBOT
willow scroll
stiff fjord
#

pasteofcode

stiff fjord
true oriole
#

How i start editing the script i back delete and its now working i litterally install jetbrain for external tool

timid ember
eternal falconBOT
timid ember
willow scroll
faint osprey
#

im kinda new to git when i set up a repository with unity how do i set up a git ignore to ignore the library folder

willow scroll
willow scroll
timid ember
timid ember
#

even after i put it twice, which for some reason made the string as 1+2(I click 11++22)

willow scroll
true oriole
timid ember
#

the error persisted

willow scroll
timid ember
#

ditto code

true oriole
true oriole
verbal dome
willow scroll
timid ember
#

CurInput=answer.ToString()

#

with a ;

stiff fjord
willow scroll
timid ember
willow scroll
willow scroll
timid ember
#

computing mathematics

#

ive never used compute but it takes string such as 4+3+15 and computes it and gives the answer back in double, which is then changed into CurInput string

stiff fjord
willow scroll
#
DataTable table = new DataTable();
table.Columns.Add("Numbers", typeof(int));

table.Rows.Add(10);
table.Rows.Add(20);
table.Rows.Add(30);

object numbersSum = table.Compute("SUM(Numbers)", string.Empty);
// 10 + 20 + 30 -> 60
#

The following example calculates the sum of the rows in the Numbers column with string.Empty filter, meaning that all numbers are included

#
| Numbers |
| ------- |
| 10      |
| 20      |
| 30      |
willow scroll
tiny bloom
#

anyone knows how to fix this?
i can't seem to know how to reproduce it but it happens often out of no where

willow scroll
tiny bloom
willow scroll
true oriole
#

i downloaded cinemachine install right but i don't see it as a tab its suppose to be beside component how do i fix it?

meager fractal
#

Okay guys so I have a scene with a play button and when I click the play button it takes me to my second scene as intended but it only lets me view the scene like this instead of letting me be the player can anyone tell me why?

verbal dome
meager fractal
#

my bad

#

I dont know what happened to all my things i had working

#

I was messing with the button screen and everythign went away on my other scene

shy ruin
#

Hey guys I'm making a dungeon like room generator, it's just hallways and stuff. I need to do occlusion of course for this because it's huge, but normal occlusion doesn't seem to work at runtime. Is there any way I can get help with this, it's the most important part of my game.

shy ruin
verbal dome
#

Or program some sort of "portal-based occlusion" yourself

#

Which I think would be the simplest way to implement it

shy ruin
#

Long hallway made out of multiple rooms

verbal dome
#

That's not an issue if you implement it correctly

shy ruin
#

This is weird, does it look like it's working?

#

It just started doing this

#

It seems to be only FOV though.

#

Biggest problem is it cannot be an occluder

verbal dome
#

Yeah I don't think that the built in occlusion is suitable for procedural stuff

#

I'm in the middle of writing my own occlusion system for generated areas. If you find something useful please ping me though @shy ruin

shy ruin
#

Ok, what should I do right now though.

verbal dome
shy ruin
#

Fine, I'll try it but the reviews say there's a ton of deprecated variables.

verbal dome
#

Fixing those would likely be easier than writing your own from scratch. I havent' found any alternatives yet

ripe oyster
#

in visual studio it sometimes gets the references and has the autofill, but now i opened a second new script and it doesn't detect any of the unity systems. not even debug.log();
does anybody know what can cause this?
so far there are 2 scripts in this project. 1 works fine, the other doesn't.

shy ruin
#

The only thing left is your portal method, any way you could point me in the direction to understand it and get working on it?

verbal dome
#

It's some pretty advanced stuff though, definitely not a beginner subject

#

@shy ruin Looking at the video series I linked it seems really complex, even for me (going into SIMD stuff etc.)
But keep searching for solutions, especially portal-based, since that should work the best for closed spaces like dungeons

shy ruin
verbal dome
#

Using cameras and custom shaders is a possibility yeah. There might be some big issues I can't think of right now

shy ruin
verbal dome
#

Btw frustum culling doesn't really help you here. An area can be in the frustum but still be occluded by a wall

#

I'd probably render the camera to a rendertexture with certain colors representing certain areas. Then use a script or a compute shader to check if an area's color is visible in the texture

shy ruin
bold saffron
#

for some reason I keep on getting this error, everything runs ok but I still get this for some reason

languid spire
quaint cave
#

hi! im making a 2d maze game in Unity for my comp sci coursework and its been working fine so far, however, after i created the playerEnemyCollision script for my game and ran the program, a few errors came up.

  1. the hearts/lives disappear from the screen (i added this as a sprite rather than ui)
  2. when i dont move the player, the enemy characters move/push the player outside the screen on its own
  3. in the console, it does not report "Game over" when the enemy and player collide.

here is my PlayerEnemyCollision script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerCollision : MonoBehaviour
{
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.transform.tag == "Enemy")
{
Debug.Log("Game Over");
}
}
}

here is my lives manager script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class LivesManager : MonoBehaviour
{
public static int lives = 3;
public SpriteRenderer[] hearts;
public Sprite fullHeart;
public Sprite emptyHeart;
private void Awake()
{
lives = 3;
}
// Update is called once per frame
void Update()
{
foreach(SpriteRenderer heart in hearts)
{
heart.sprite = emptyHeart;
}
for (int i = 0; i < lives; i++)
{
hearts[i].sprite = fullHeart;
}
}
}

eternal falconBOT
tender stag
#

how can i check if the event has anything inside of it?

#

before calling it

#

which one would i use

#

this works

karmic talon
#

hi i have a quick question i have N items and i want to store them
actually i'm making a big Dictionary where i have
Dictionary<string, Dictionary<string, Dictionary<string, Dictionary<int, Dictionary<int, Dictionary<string,>>>>>>

where each dictionary take a specific value :
DisplayName
ID
CustomData (json file)
Quantity
Price
Currency
can i do it easier ? i'm actually stuck with this format

languid spire
keen dew
#

At a minimum make a struct or class with those fields and put them in an array or maybe in one dictionary with id as the key

polar acorn
quick cobalt
#

hi stupid question, is there an offset to the mouse vector3? Like my Input.Mouseposition is so far from my original screen (while the screen being at 0.0.0)

#
    private void OnMouseDrag()
    {
        mousePos = Input.mousePosition;
        this.transform.position = mousePos;
    }``` i tried something super simple
languid spire
#

you need to use ScreenToWorldPoint to convert it

quick cobalt
#

Thank you, thought so i was missing something

hallow acorn
languid spire
#

how can you compare a tag on a null object?

timid ember
hallow acorn
#

does it work if i put the CurrentlyGrabbed = null; behind the if statement?

#

also who the actual f did you make the colors there

languid spire
#

yes, it would work if you set it to null after the if because it is no longer used.
colours come from properly posting inline !code

eternal falconBOT
hallow acorn
#
 if(Currently = null)
languid spire
#

read the message again, with care

#

got it

hallow acorn
#

yoo thats cool ty

languid spire
#

fyi, should be ==

hallow acorn
#

yeah youre right

toxic void
#

Hey, I made a basic cc (rigidbody), and for some reason it seems to be very choppy, you can see the tree in the left, and every child and parent is on scale 1 and the camera is a child of an empty which updates to the position of an empty on the player called cameraPos. Help is appreciated.

keen dew
#

You'll have to show the code

#

but why is the camera not directly a child of the player

stiff crag
#
public class TriggerFix : MonoBehaviour
{
    private void OnTriggerEnter(Collider other)
    {
            Debug.Log("Touched collider: " + other.name);
    }
}```
I have an object that has a collider set as a trigger with a script that checks for OnTriggerEnter, which works, however if any other trigger is being activated, it executes this too
How can I restrict this OnTriggerEnter to that one BoxCollider?
toxic void
keen dew
#

Why would it do that?

toxic void
# keen dew You'll have to show the code
public class PlayerMovement : MonoBehaviour
{
    // General variables
    public float movementSpeed;
    public float groundDrag;
    

    // Collision and jumping
    bool isOnWalkableGround = false;
    public float playerHeight;
    public LayerMask ground;

    // Movement variables
    float forwardInput = 0f;
    float horizontalInput = 0f;
    Vector3 moveDirection;
    Rigidbody rb;
    
    void Start() {
        rb = GetComponent<Rigidbody>();
        rb.freezeRotation = true;
    }

    void Update() {

        // Ground check
        isOnWalkableGround = Physics.Raycast(transform.position, Vector3.down, playerHeight * 0.5f + 0.2f, ground);

        UpdateInput();
        ControlVelocity();

        // Drag
        if (isOnWalkableGround) {
            rb.drag = groundDrag;
        } else {
            rb.drag = 0f;
        }

    }
    
    void FixedUpdate() {
        MovePlayer();
    }
    
    private void UpdateInput() {
        forwardInput = Input.GetAxisRaw("Vertical");
        horizontalInput = Input.GetAxisRaw("Horizontal");
    }

    private void MovePlayer() {
        moveDirection = transform.forward * forwardInput + transform.right * horizontalInput;
        rb.AddForce(moveDirection.normalized * movementSpeed * 10f);
    }

    private void ControlVelocity() {
        Vector3 flatVel = new Vector3(rb.velocity.x, 0f, rb.velocity.z);

        if (flatVel.magnitude >= movementSpeed) {
            Vector3 factoredVel = flatVel.normalized * movementSpeed;
            rb.velocity = new Vector3(factoredVel.x, rb.velocity.y, factoredVel.z);
        }
    }
}

keen dew
#

This doesn't have the code that moves the camera. But I suggest you just make the camera a child of the player if the only reason it's not already there is to avoid lag

toxic void
#

Alright, thanks

#

It didn't fix the issue. By the way, the stuttering only happens when I move my camera and move at the same time. It also happens but only a little bit when moving only the camera, so moving might just be amplifying it.

#

So here's the camera movement script:

public class CameraHandler : MonoBehaviour
{

    public float xSensitivity;
    public float ySensitivity;

    public Transform playerTransform;


    float xRotation;
    float yRotation;

    // Start is called before the first frame update
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    // Update is called once per frame
    void Update()
    {
        float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * xSensitivity;
        float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * ySensitivity;

        xRotation -= mouseY;
        xRotation = Math.Clamp(xRotation, -90f, 90f);
        yRotation += mouseX;

        transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
        playerTransform.rotation = Quaternion.Euler(0, yRotation, 0);
    }
}
stiff crag
stiff crag
toxic void
#

The OnTriggerEnter has a collider parameter, I think it has a tag property.

stiff crag
#

Yeah, and I can check what has collided with the trigger, however the other collider isn't the issue
Currently any trigger I touch with the other collider calls the event, somehow

toxic cloak
#

is haset only used to avoid duplicates or it has any other use?

toxic void
stiff crag
toxic cloak
toxic void
stiff crag
toxic void
tiny bloom
#

When I open this prefab in the prefab editor it shows like this (just white blank image)
but in my game or in the editor, it looks fine
why?

tiny bloom
tiny bloom
#

why does it reset in prefab editor though?

toxic cloak
toxic cloak
verbal dome
toxic void
#

Is there a way to create a vector instance with magnitude and angle?

#

I mean I know I can implement it but before I do I wanna know if there already is a way

toxic void
toxic void
#

2d vector in my case

verbal dome
#

You can use Mathf.Sin and Mathf.Cos and then multiply the vector with the magnitude

#

Oh and Mathf.Deg2Rad assuming you want to use degrees not radians

#

Or ditch the trigonometry and do Quaternion.Euler(0, 0, angle) * new Vector2(0, magnitude)

stiff crag
# toxic cloak https://docs.unity3d.com/ScriptReference/LayerMask.html

Isn't this for including/excluding colliders? The issue is not that the wrong collider calls the event, but that in area, where are multiple triggers and there is 1 with this script, although if the collider enters any trigger (no matter if the trigger has or not the script) the event gets called

#

Ex. Trigger1 with the script, Trigger2 without the script
If collider named "player" enters Trigger1, the event gets called, but somehow, if the same collider enters Trigger2, the same event gets called, even though the Trigger2 doesn't have the said script

toxic cloak
toxic void
stiff crag
verbal dome
stiff crag
verbal dome
#

* Time.deltaTime makes it inconsistent.

toxic void
verbal dome
#

I wish those youtube tutorial makers also knew...

toxic cloak
faint osprey
#

is there a way to trigger functions in the animation timeline

stiff crag
faint osprey
#

thanks

#

is there a reason why my animation is only triggering once through code

#
    {
        m_RB.linearVelocity = Vector2.zero;
        m_RB.constraints = RigidbodyConstraints2D.FreezePosition;
        m_Anim.Play("SlamAnim");
        //m_RB.AddForce(Vector2.down * m_SlamStrength, ForceMode2D.Impulse);
    }```
tender stag
#

public List<RaycastHit> sortedHits;

// In update for example
sortedHits.Clear();

#

its giving me an error on the sortedHits.Clear();

rich adder
#

so List is never put in the inspector, therefore is never initialized by Unity

tender stag
#

i dont need it in the inspector

rich adder
#

with that said you need to initialize it yourself

#

the list is null because its not initialized

tender stag
#

private List<RaycastHit> sortedHits = new List<RaycastHit>();

rich adder
#

correct

tender stag
#

u mean this

#

alright

lost maple
#

How to convert color to HEX please
cuz i've strucks this error

rich adder
#

holy flashbang

zenith cypress
#

It's X not x

lost maple
#

No X lead to the same mistake

mighty compass
#

goodmorningyall, wee are about to work on some more building mechanics! lol

#
using System.Collections.Generic;
using UnityEngine;

public class Building : MonoBehaviour
{
    // Variables
    private GameObject playerObject;
    private GameObject cameraObject;

    private KeyCode buildToggleKey = KeyCode.B;
    private int buildKey = 1;
    private int destroyKey = 0;

    [SerializeField]
    private bool buildMode;

    void Start(){
        playerObject = GameObject.Find("Player");
        cameraObject = GameObject.Find("PlayerCamera");
        buildMode = false;
    }


    void Update(){

        // Toggling build mode.
        if (!buildMode && Input.GetKeyDown(buildToggleKey)){
            buildMode = true;
        }

        // Methods that occur during building.
        else if (buildMode){
            if (Input.GetKeyDown(buildToggleKey)){
                buildMode = false;
            }

            // Build.
            if (Input.GetMouseButtonDown(buildKey)){
                build();
            }

            // Destroy.
            if (Input.GetMouseButtonDown(destroyKey)){
                destroy();
            }
        }
    }

    void build(){
        Vector3 buildPos = transform.TransformPoint(cameraObject.transform.forward * 3);
        GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);

        // Transform the coordinates of local space to world space.
        cube.transform.position = new Vector3(Mathf.Floor(buildPos.x), Mathf.Ceil(buildPos.y), Mathf.Floor(buildPos.z));
    }

    void destroy(){

    }
}
```How do yall think I should go about making a block that outlines the block I am about to place in my building programming.
short hazel
mighty compass
#

Should I make it create a transparent object in every valid space the player can place a block, and delete the object everytime they move, or should I do some sortof shader programming?

zenith cypress
#

oh right x is lowercase LUL

mighty compass
#

Also I know my logic for placing blocks isn't the best at the moment, I just wanted something functional xD

vagrant fjord
#

i have a weapon switch mechanic and after a number of switches my sword rotated and stays in that position, any fixes?

vagrant fjord
#

how?

verbal dome
#

Do you honestly think anyone can answer that without seeing your code and other details 🤔

vagrant fjord
#

yeah sorry bro 😅

lapis frigate
#

can anyone explain to me why am i getting a null refrence error when the level system is crealy assinged to the player GO along with the scripts

mighty compass
#
        Vector3 buildPos = transform.TransformPoint(cameraObject.transform.forward * 3);
        GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);

        // Transform the coordinates of local space to world space.
        cube.transform.position = new Vector3(Mathf.Floor(buildPos.x), Mathf.Ceil(buildPos.y), Mathf.Floor(buildPos.z));
    }``` Okay quick question, How can I make this block transparent, I saw some tutorial of a dude creating a stencil
verbal dome
#

Use Awake/Start for initialization instead

tender stag
#

is it possible to make your own attribute which would expose the variable in the editor

#

but make it read only?

#

so you couldnt assign anything by dragging or clicking

#

you would only be able to assign it through script

zenith cypress
#

If you using something like NaughtyAttributes it has a ReadOnly attribute for that

vagrant fjord
zenith cypress
#

It's a free asset, yes

tender stag
#

is that the one

#

or is this some rip off

rich adder
#

using NaughtAttributes if you only need Readonly is a bit overkill

#

iirc someone had a script that just made that 1 specific attribute

tender stag
lapis frigate
rich adder
lapis frigate
#

even though the unitLevel did got the value of the playerLevel

acoustic arch
#

inspector

verbal dome
lapis frigate
verbal dome
tender stag
rich adder
acoustic arch
#

levelManager.playerLevel;
^ this is probably whats null

lapis frigate
#

not null just debugged it

lapis frigate
#

even though it works...

#

thats wierd

verbal dome
#

Type t:playerscript in the scene view search

lapis frigate
#

nevermind

#

found my mistake

verbal dome
#

What was it

lapis frigate
#

I did not assinged it to the enemy game object

#

thats because the level system is for the player only

#

and I didn't think about it but I shouldn't have created the refrence to the levelSystem in the unit class

#

but in the player class only so ill fix that

mighty compass
#
        Vector3 buildPos = transform.TransformPoint(cameraObject.transform.forward * 3);
        GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);

        Material transparentMaterial = "Assets/Materials/TransparentBuildingMaterial";

        MeshRenderer cubeMesh = cube.GetComponent<MeshRenderer>();
        cubeMesh.material = transparentMaterial;

        // Transform the coordinates of local space to world space.
        cube.transform.position = new Vector3(Mathf.Floor(buildPos.x), Mathf.Ceil(buildPos.y), Mathf.Floor(buildPos.z));
    }``` I'm attempting to load my material and apply it to this cube, what is a way that I can do this
rich adder
#

or better use a reference in inspector

mighty compass
#

I tried resource load, but it said to place that in an awake event or something?

rich adder
#

instead of .material you should target the .sharedMaterial when possible

mighty compass
#

It wasn't clear what to do

#

kk

queen adder
rich adder
#

private Material myMat
awake()
myMat = Resources.Load("someMaterial")

mighty compass
#

Alright i'll learn addressables, if they're better?

#

Where can I learn about addressables

rich adder
#

depends what you're doing, addressable might be overkill here

mighty compass
#

I might need it eventually

mighty compass
#

Because I'm going to be placing a variety of objects eventually

queen adder
#

They are better but in some cases, navarone's solution is good too

mighty compass
#

And I'm assuming addressables make finding objects and materials to load into the scene, more efficient?

rich adder
#

yes

#

cause it loads them in memory when they are needed

mighty compass
#

Awesome

rich adder
#

instead of all at once

queen adder
mighty compass
#

Also I cant seem to find the resource management in the asset management dropdown

#

is it a package I have to import?

#

nvm i foudn the packaage

queen adder
# mighty compass What is FBX

If i were to simply tell, it is a type of 3D object. If it configured, it may include it's animations, textures. For example a literal Chicken.

rich adder
mighty compass
mighty compass
rich adder
#

I mean you could just have a bunch of SerializeField on the script and just drop your materials there and get going

#

thought you were trying to do over the net stuff or load large assets

frigid veldt
#

Hello, working on a little dialogue system with a total of 5 audio samples.
Currently made the text work using a Canvas and TextmeshPro, and I used string to display these texts
I wanted to do the same for the audio, put them in a string so theyre in a certain order, but that is not a thing

Any other ideas how to do this effectively?

queen adder
#

Think simple. You seem capable of doing that system without any help at all

rich adder
frigid veldt
#

Been on it for an hour but I cant think of anything within my capability

frigid veldt
rich adder
#

technically strings are arrays

#

of char
but I mean an array of audio basically

queen adder
#

Ah i was wrong 🥺

frigid veldt
rich adder
#

ofc put a check there so you don't go outta bounds 🕶️

frigid veldt
frigid veldt
#

oh hahaha

rich adder
#

but string itself is technically char[] 😅

#

well its complicated

frigid veldt
#

I used 'private int audioIndex;'

mighty compass
#

Load is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour 'Building' on game object 'Player'. Getting this error in here ```\n`````` void transparentBuildVisualizer(){
if (currentBlock != null){
Destroy(currentBlock);
}

    Vector3 buildPos = transform.TransformPoint(cameraObject.transform.forward * 3);
    GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);

    MeshRenderer cubeMesh = cube.GetComponent<MeshRenderer>();
    cubeMesh.material = transparentMaterial;
    currentBlock = cube;

    // Transform the coordinates of local space to world space.
    cube.transform.position = new Vector3(Mathf.Floor(buildPos.x), Mathf.Ceil(buildPos.y), Mathf.Floor(buildPos.z));
}``` ```\n``` Declaration is: ```    [SerializeField]
private Material transparentMaterial;```
rich adder
#

you seem to have it from here then (make the type AudioClip ofc)

mighty compass
#

I'm going to learn addressables once I have more objects lol

frigid veldt
rich adder
rich adder
frigid veldt
#

Cheers UnityChanThumbsUp

mighty compass
#

!bot

rich adder
eternal falconBOT
mighty compass
#

I forgot i favourited the site already

rich adder
mighty compass
#

There's no line error

#

It's just saying I cant use load in a monobehavior script

verbal dome
#

I don't see Resources.Load used anywhere. Is this an addressables thing (are you even using it now)?

#

Did you save the script..?

mighty compass
#

I guess I'm implicity loading with the SerializeField

#

for the Material?

#

possibly

rich adder
#

is this even the correct script lol

mighty compass
#

yes

verbal dome
#

According to the error it happened in Building script yeah

rich adder
#

oh right

mighty compass
#

It doesn't like the fact im loading a material lol

rich adder
#

save the script you sent, clear all console messages and start agian

slender nymph
#

a serialized field does not use Resources.Load, that would not be the cause of it. there is nothing wrong with serializing a reference to a material

dry geyser
#

Can anyone help me with a function not popping up in here: (it is a public function)

ivory bobcat
dry geyser
#

yup

ivory bobcat
#

Does the function have the correct signature?

dry geyser
#

whats that mean

ivory bobcat
dry geyser
#

the white

ivory bobcat
# dry geyser

Normally Unity inspector callback/action references only allow single parameter functions.

dry geyser
#

ok, ill remove a parameter and see if that fixes it

dry geyser
ivory bobcat
#

Nope. Have another component reference the Text and set a float field then reference that component from the button or whatever that you've not shown us yet.

misty rose
#

can someone help me understand why the hitinfo parameter is not being recognised, i think im doing something stupid but i cant get my head around it?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RaycastGun : MonoBehaviour
{
    public Transform playerPos;
    public float maxShootDistance;

    // Update is called once per frame
    void Update()
    {
        RaycastHit hitInfo;
        Ray2D ray = new Ray2D(playerPos.position, Vector2.right);

        if (Physics.Raycast(ray, out hitInfo, maxShootDistance)); // broken line
        {
            
        }
    }
}
misty rose
#

havent run the game but the line is red, here look

ivory bobcat
#

What does the error say in the console?

misty rose
#

let me check

ivory bobcat
#

You wouldn't need to run the application to see the error in the console

misty rose
#

i think i see the problem

#

yep

#

im dumb

#

sorry for wasting yall time lol

ivory bobcat
misty rose
#

thanks

ivory bobcat
#

If you're wanting to use the 2d variant, you'll need to use Physics 2d etc

mighty compass
dusk tusk
#

One second Im opening discord

#

"Your not connected" 🤓☝️

#

Eh I'll just retype it

rich adder
#

read bot msg ⬇️ !code

eternal falconBOT
dusk tusk
#
void Update()
    {
        Rigidbody2D rigidbody = GetComponent<Rigidbody2D>();

        if (Input.GetKey(KeyCode.D))
        {
            rigidbody.position += Vector2.right * Time.deltaTime * moveSpeed;
        }
        else if (Input.GetKey(KeyCode.A))
        {
            rigidbody.position += Vector2.left * Time.deltaTime * moveSpeed;
        }
        
        if (Input.GetKeyDown(KeyCode.Space))
        {
            if (rigidbody.velocity.y == 0)
            {
                rigidbody.AddForce(new Vector2(0, jumpHeight), ForceMode2D.Impulse);
            }
        }
    }```
polar acorn
dusk tusk
#

True...

polar acorn
#

if the intention for that is to check if you're on the ground, you should probably use something like a raycast or spherecast to check if there's ground below your feet instead

dusk tusk
#

Id rather not...

#

It took me 2 hours until I gave up

#

I'll just give it a little wiggle room

#

rigidbody.velocity.y < 0.5
Would this work?

#

Actually lemme check

rancid tinsel
#

im looking at inheritance rn for uni but im struggling to see a good example for why i would use it - does anyone have one?

#

my personal issue is it seems like a big headache for something I could just achieve with a boolean, switch statement and an admittedly longer script

#

unless im just not seeing the bigger picture

dusk tusk
#

I think

rancid tinsel
#

i mean longer scripts are more of a hassle to work with, especially when they aren't yours (working in a team) so not necessarily

dusk tusk
#

True

rancid tinsel
#

but at the same time i feel like id find it easier to work with a longer script than it being split into parent and child classes

polar acorn
# rancid tinsel im looking at inheritance rn for uni but im struggling to see a good example for...

Make a script - "Weapon". Has things like damage, durability, whether it's one or two handed, etc.
Then you could make a thousand scripts - "Baseball bat", "Chainsaw", "Park bench", "Cash Register", etc. that all inherit from Weapon.

Your inventory becomes List<Weapon> and your current weapon is a variable of type Weapon and you can very easy do something like duraText.text = currentWeapon.durability without even caring about which of those thousand child objects you currently have in that slot

mighty compass
#
        float yRot = 0;
        switch (true){
            case (buildRot.y <= 45):
                yRot = 0;
                break;
            case buildRot.y > 45 && buildRot.y <= 90:
                yRot = 90;
                break;
            case buildRot.y > 90 && buildRot.y <= 180:
                yRot = 180;
                break;
            case buildRot.y > 180 && buildRot.y <= 270:
                yRot = 270;
                break;
        }```Why isn't my switch working, not sure what c# switch statements look like
polar acorn
#

so that would probably be why

#

Well, actually, it could be equal to any of those, if those conditions evaluate to true 🤔

mighty compass
#

is rotation 0-359? as a quaternion, like the y value of a quat

polar acorn
#

The y value of a quaternion has nothing to do with the Y axis of normal Euclidian space, it's a normalized 4D value including imaginary numbers to express an orientation

mighty compass
#

Assets\Scripts\PlayerScripts\ClientSideScripts\Building.cs(99,18): error CS0150: A constant value is expected Also this is the error i mgetting

mighty compass
polar acorn
#

Yeah, you can't use an expression as a switch case. The only way this would be valid is if buildRot was a const, which is what I meant by "technically true"

mighty compass
#

Ah I see

polar acorn
#

and you can combine X and Z rotations to gain the same orientation you could by having a value on Y

mighty compass
#

coolio

#

What does rotation even return then if not 90, 180 etc

#

is it like some random float value

polar acorn
#

If you ever find yourself trying to deal with individual components of a quaternion, don't

mighty compass
#

I see hahaha

#

I have to limit the rotation of these wall assets I've made, so they place correctly in a grid block

#

dependent on player rotation to grid space they're placing it in

#

euler angles would be waht I want to use then?

polar acorn
#

Generally, you should work with directions rather than angles. You can get the direction it starts facing, and compare it to a world direction. Dot product is 1 when the two directions are facing the same direction, 0 when perpendicular, and -1 when opposite. So, you can get the current forward direction, and compare it to Vector3.forward, Vector3.left, Vector3.backward, and Vector3.right. Find which one has the highest Dot Product, that's the direction the object is "closest to" facing

#

That way you don't have to deal with positive/negatives, or non-Y rotations expressing the same direction

mighty compass
#

Awesome, thankyou. That's great

marble hemlock
#

is it better to write your own inputs for movement with character controller or simply use the input manager

#

im about to just throw out the entire movement script and start over because i feel like with the way i've written it i cant really add crouching or jumping. originally i had no intentions for those because it didnt really cross my mind as that important. i likely wont do the jumping, but crouching will likely be added

#

physics vs character controller
my greatest enemy

valid turtle
#

I´ve been struggeling the past hour with the following problem:

I made some code in a flappy bird clone to add a point every time I go trough a trigger between pipes. Works perfectly

Now I want to make it so that if I get a game over I cant get more points even if I still go trough another pipe, but no matter what I do the points either stay at 0 the whole time or the code dosen´t work at all.

WHat should I do?

deft grail
eternal falconBOT
valid turtle
#
public class MiddeloPipoScripto : MonoBehaviour

{
    public LogicoScripto logic;
    public SChloppyScript SchloppyLebt;
    public LogicoScripto playerScore;
    // Start is called before the first frame update
    void Start()
    {
        logic = GameObject.FindGameObjectWithTag("Logic").GetComponent<LogicoScripto>();
    }

    // Update is called once per frame
    void Update()
    {

    }

    private void OnTriggerEnter2D(Collider2D collision)
    {

        if (collision.gameObject && SchloppyLebt == true)
        {
            logic.addScore(1);
        }
    }
}
deft grail
valid turtle
#

in another script. One sec

#
public class SChloppyScript : MonoBehaviour
{
    public Rigidbody2D myRigidbody;
    public float flyStrenght;
    public LogicoScripto logic;
    public bool SchloppyLebt = true;

    // Start is called before the first frame update
    void Start()
    {
        gameObject.name = "Schloppy";
        logic = GameObject.FindGameObjectWithTag("Logic").GetComponent<LogicoScripto>();

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space) == true && SchloppyLebt == true)
        {
            myRigidbody.velocity = Vector2.up * flyStrenght;
        }
        
        if(transform.position.y > 4.5)
            {
            logic.gameOva();
            SchloppyLebt = false;
        }

        if(transform.position.y < -4.5)
        {
            logic.gameOva();
            SchloppyLebt = false;
        }

    }
    private void OnCollisionEnter2D(Collision2D collision)
    {
        logic.gameOva();
        SchloppyLebt = false;
    }
}
#

aat the bottom,

deft grail
valid turtle
#

yes that code I sent runs pefectly

deft grail
#

ah

#

nvm

#

i see the problem

deft grail
#

you are just checking if your script variable is true

#

your not checking the actual bool itself

marble hemlock
#

i might just throw out my script and character controller and work with rigid bodies instead

#

never really done it before so this might be a pain

valid turtle
deft grail
deft grail
#

the . access a property

valid turtle
#

Do I put that after the && ?

deft grail
valid turtle
#

I get CS0117

Basically MyBool dosent have a reference. But if I change MyBool to what I called the alive status then it becomes CS0120

marble hemlock
#

ye i'll just set the player to be a kinematic rigid body and code the movement

valid turtle
#
 private void OnTriggerEnter2D(Collider2D collision)
    {

        if (collision.gameObject && SChloppyScript.SchloppyLebt == true)
        {
            logic.addScore(1);
        }
    }
}
marble hemlock
#

the player itself is not what needs to be affected by physics, but the player's movements will be applying physics effects to other objects it interacts with

#

so if it runs into something (that also happens to be a rigid body that isnt kinematic), it should push that thing

#

how fun :(

deft grail
valid turtle
#
public SChloppyScript SchloppyLebt;
#

isnt that the reference?

deft grail
#

in this code

ashen frigate
#

im trying to add an partical effect and after 1 use it gets destroyed do u know how to fix it ?
MissingReferenceException: The object of type 'ParticleSystem' has been destroyed but you are still trying to access it.

valid turtle
#

I am? 😭

deft grail
deft grail
#

look

ashen frigate
#

im not destoying it it just destoying it self

#

void CreateSmoke() { SmokeEffect.Play(); } void CreateDoublejumpSmoke() { DoublejumpSmoke.Play(); }

#

this is my function to use it

deft grail
#
//First Script
public class MyScript : MonoBehaviour
{
  public bool MyBool;
}

//Other Script
public MyScript myScript;

if(myScript.MyBool == true) { myScript.MyBool = false; }
deft grail
#

what you should do is just de activate it, or Instantiate and play one instead of playing the same one

#

by making a prefab and instantiating and playing it

deft grail
valid turtle
#

give me a bit

marble hemlock
#

i was panicking and worrying id have to redo the entire thing and replace all the components but turns out i can just remove the character controller component UnityChanThumbsUp

valid turtle
#

The problem I have is that it says it needs an object reference, but I have that reference like I said b4. Im so confused

deft grail
#

what you have done basically is:

public MyScript MyBool;
if(MyBool)
``` which is wrong, the compiler doesnt just guess you want to use `MyBool` of `MyScript` because you named your variable that
valid turtle
#
/// I have this
  public SChloppyScript SchloppyLebt;

/// and I try this
SChloppyScript.SchloppyLebt == true)
deft grail
valid turtle
#

Ohhh okay

deft grail
# valid turtle Ohhh okay

this line public SChloppyScript SchloppyLebt; can be named absolutely anything, it doesnt relate to just 1 variable you want to access from it, you TELL it what variable you want to access via the . then typing the name of the variable you want

valid turtle
#
  if (collision.gameObject && SchloppyLebt.SchloppyLebt == true)
        {
            logic.addScore(1);
        }
        else
        {
            logic.addScore(0);
        }
      
    }
}
#

this might work then?

deft grail
valid turtle
#

Okay now its just not adding score at all anymore

#

Wth

#

xD

deft grail
valid turtle
#

yes

marble hemlock
#

i added the component to begin with

deft grail
# valid turtle yes

before the if statement do Debug.Log($"Collided with: {collision.gameObject.name}, bool is: {SchloppyLebt.SchloppyLebt}");

#

and see what it prints

valid turtle
#

NullReferenceException: Object reference not set to an instance of an object
MiddeloPipoScripto.OnTriggerEnter2D (UnityEngine.Collider2D collision) (at Assets/MiddeloPipoScripto.cs:25)

deft grail
#

i assume not

valid turtle
#

Uhh wdym by that

deft grail
valid turtle
#

you mean here

deft grail
#

no

#

on the other script

#

MiddeloPipScripto

#

which isnt on this game object

valid turtle
deft grail
valid turtle
#

Yes

deft grail
#

then go to that game object

valid turtle
#

okay

#

I did

deft grail
#

now there should be an empty slot

valid turtle
deft grail
#

oh right its a prefab

#

so you wont be able to drag it in

valid turtle
#

jup

deft grail
#

but Find should be avoided as much as possible usually

valid turtle
#

Where should I use find?

deft grail
#

the same way as you do multiple times already

valid turtle
#
void Start()
    {
        logic = GameObject.FindGameObjectWithTag("Logic").GetComponent<LogicoScripto>();
    }
#

like here

deft grail
#

yeah

#

but for SChloppyScript this script instead

valid turtle
#

what would the code look like? I never wrote a find function

deft grail
#

i see multiple of them

#

in your code

valid turtle
#

Sorry Im just so new to this. What do you mean by find?

cosmic dagger
deft grail
#

or if it has a tag you can use the FindWIthTag

valid turtle
#

That probably wont work, because I added a tag to that gameobejct

#

Everything will not work if I do that I think

deft grail
#

your just finding a game object by name

#

then accessing the component from it

valid turtle
#

Im so confused as well

deft grail
valid turtle
#

I know Im sorry

deft grail
#

as simple as that

valid turtle
#

I put that into start

#

that whole thing

deft grail
#

yes

#

its just 1 line, "that whole thing" sounds a bit exaggerated lol

valid turtle
#

To me it looks so confusing because I barely understand what it means so I call it "that whole thing"

crimson whale
#

Not sure if this is a code issue, so please don't jump down my throat. I don't know which channel to post this in.

I have a prefab containing a parent "Struct_Cannon" with no mesh attached to it, and two children. One a cube and one a cylinder.

When I instantiate the prefab, the cube does not come along, and simply isn't present.

Nothing gets deleted until the structure has less than 1 health, and here's the instantiation code:

    if (!spawnedStruct) {
        GameObject curCannon = Instantiate(cannon, new Vector3(0, 0.5f, 0), Quaternion.identity);
        StructInitiate structInitiate = curCannon.GetComponent<StructInitiate>();
        structInitiate.structActive = true;
        structInitiate.health = 200f;
        spawnedStruct = true;
    }
    else {
        Debug.Log("Cannot place: cannon in way");
    }       
}```

The body child is active and on a plane the camera can see, but it's not being added to the scene at all.

Any help is greatly appreciated.
valid turtle
#

SchloppyScript is Type but is being used as Variable is now the issue

deft grail
crimson whale
valid turtle
deft grail
valid turtle
#

I just wrote it fast

valid turtle
#

I think

#

I dont know

#

Just assuming

deft grail
valid turtle
#

But why "YourObjectNameThatHasThe (SChloppyScript)"?

#

why SChlopyScript

deft grail
#

idk what you name it

#

Schloppy thats what you name it

#

SchloppyLebt = GameObject.Find("Schloppy").GetComponent<SChloppyScript>();

valid turtle
#

Wait I think I understand my mistake

#

Do i put it Voidstart of the Bird script or the trigger script?

deft grail
valid turtle
#

oh

#

lmao

deft grail
#

the bird script is already the bird script

#

why would it find itself

valid turtle
#

I was like;
why would I find it where I already am

#
void Start()
    {
        logic = GameObject.FindGameObjectWithTag("Logic").GetComponent<LogicoScripto>();
        SchloppyLebt = GameObject.Find("Schloppy").GetComponent<SChloppyScript>();
    }
crimson whale
#

Hey @deft grail you see any immediate issues with what I'm doing? Can't figure this out

valid turtle
#

like this

#

or remove the first line?

deft grail
crimson whale
#

But the cube just isn't being included in instantiation

valid turtle
deft grail
#

this is why Find isnt good either, because if you rename it boom the code is broken

valid turtle
#

So what I need to find is actually:

"SchloppyLebt" right?

#

for the isAlive code

deft grail
valid turtle
#

yes

deft grail
#

you cant find the bool, but you can find the script

#

thats your goal yes, find the script

valid turtle
#
SchloppyLebt = GameObject.Find("SchloppyLebt").GetComponent<SChloppyScript>();

#

like that

#

I think

crimson whale
#

Found the issue: I had the script intended for the prefab as a whole attached to the child object.

deft grail
valid turtle
#
void Start()
    {
        gameObject.name = "Schloppy";
deft grail
valid turtle
#

Okay okay

#

understood

#

and now it should work?

#

or do I need to add anything else?

deft grail
valid turtle
#
public class MiddeloPipoScripto : MonoBehaviour

{
    public LogicoScripto logic;
    public SChloppyScript SchloppyLebt;
    public LogicoScripto playerScore;
    // Start is called before the first frame update
    void Start()
    {
        logic = GameObject.FindGameObjectWithTag("Logic").GetComponent<LogicoScripto>();
        SchloppyLebt = GameObject.Find("Schloppy").GetComponent<SChloppyScript>();
    }

    // Update is called once per frame
    void Update()
    {

    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        Debug.Log($"Collided with: {collision.gameObject.name}, bool is: {SchloppyLebt.SchloppyLebt}");

        if (collision.gameObject && SchloppyLebt.SchloppyLebt == true)
        {
            logic.addScore(1);
        }
      
    }
}
deft grail
deft grail
#

its been confusing so far so might be missed

valid turtle
#

lets see

valid turtle
#

OMG
IT WORKS

#

I LOVE YOU

#

Now I need to understand why it worked and then everything is perfect xD

deft grail
valid turtle
#

If its okay for you Ill ask you a question

#

maybe I understand then

deft grail
#

yeah sure

heady sleet
#

can someone help me find the right refrence?

#

using BepInEx;
using UnityEngine;

[BepInPlugin("com.yourname.controllerrotator", "Controller Rotator", "1.0.0")]
public class ControllerRotator : BaseUnityPlugin
{
private void Update()
{
// Check if the right trigger (GrabPinch) is pressed
if (SteamVR_Actions.default_GrabPinch.GetStateDown(SteamVR_Input_Sources.RightHand))
{
RotateController();
}
}

private void RotateController()
{
    // Find the tracked object for the right controller
    var trackedObject = GameObject.FindObjectOfType<SteamVR_TrackedObject>();

    if (trackedObject != null && trackedObject.isValid)
    {
        // Get current rotation and apply a 90-degree rotation
        Quaternion currentRotation = trackedObject.transform.rotation;
        Quaternion newRotation = currentRotation * Quaternion.Euler(90, 0, 0);
        trackedObject.transform.rotation = newRotation;
    }
    else
    {
        Logger.LogError("Tracked object is not valid.");
    }
}

}

#
using BepInEx;
using UnityEngine;

[BepInPlugin("com.yourname.controllerrotator", "Controller Rotator", "1.0.0")]
public class ControllerRotator : BaseUnityPlugin
{
    private void Update()
    {
        // Check if the right trigger (GrabPinch) is pressed
        if (SteamVR_Actions.default_GrabPinch.GetStateDown(SteamVR_Input_Sources.RightHand))  //I do not have the refrence to these actions
        {
            RotateController();
        }
    }

    private void RotateController()
    {
        // Find the tracked object for the right controller
        var trackedObject = GameObject.FindObjectOfType<SteamVR_TrackedObject>();

        if (trackedObject != null && trackedObject.isValid)
        {
            // Get current rotation and apply a 90-degree rotation
            Quaternion currentRotation = trackedObject.transform.rotation;
            Quaternion newRotation = currentRotation * Quaternion.Euler(90, 0, 0);
            trackedObject.transform.rotation = newRotation;
        }
        else
        {
            Logger.LogError("Tracked object is not valid.");
        }
    }
}
eternal falconBOT
valid turtle
#
/// This is a reference right?
 public SChloppyScript SchloppyLebt;

/// so why did we need to put this here
SchloppyLebt = GameObject.Find("Schloppy").GetComponent<SChloppyScript>();
deft grail
#

try commenting the second line with //

#

and see what happens

valid turtle
#

commenting?

deft grail
valid turtle
#

oh wait

#

okay

deft grail
#

with // or /* */ you can comment

valid turtle
#

Understood

heady sleet
#

What do I do now?

#

its giving me this

deft grail
valid turtle
deft grail
valid turtle
#

So the reason I put

public SchloppySscript SchloppyLebt;
#

is not to tell the current script to do anything with the other script?

valid turtle
deft grail
heady sleet
deft grail
#

(which is why both of you lack the basics of C# and Unity)

valid turtle
heady sleet
#

But it needed something called "Valve.VR" Which I can't get because it's refrences in "Assembly-CSharp"

valid turtle
#

like 2 days

#

literally

heady sleet
#

this is my first day

deft grail
deft grail
heady sleet
#

I don't even have unity installed on my system

#

Plus

#

I (think)

#

I know the problem

#

I can't refrence "Assembly-CSharp"

deft grail
heady sleet
#

it just becomes gray

#

(and yes I have it in my refrences)

deft grail
heady sleet
deft grail
#

i dont think thats a thing

heady sleet
#

wdym?

valid turtle
deft grail
heady sleet
heady sleet
valid turtle
# deft grail yeah

And I use:

public SChloppyScript SchloppyLebt;

To make the current script able to work with content from SChloppyScript, right?

deft grail
#

i dont think thats a thing

heady sleet
heady sleet
valid turtle
deft grail
#

same way you can do using System; etc

heady sleet
valid turtle
ashen frigate
valid turtle
deft grail
valid turtle
deft grail
#

your issue has nothing to do with c#

heady sleet
#

(how do u do the "using" thing btw?)

valid turtle
#
SchloppyLebt = GameObject.Find("Schloppy").GetComponent<SChloppyScript>();
// This does something else than making my script able to work with content from another script?
deft grail
heady sleet
#

ohhh

#

ok

#

thx

#

text

#

nice

deft grail
heady sleet
#

U know, your right

#

vr may be too hard

#

Is there a easy unity game you think would be easy to mod?

deft grail
deft grail
heady sleet
#

ewwy

#

no vrchat

deft grail
heady sleet
#

Right

#

And that was my problem

deft grail
heady sleet
#

No

#

I think you need OpenXR

#

or something along those lines.

deft grail
#

well either way, there you go thats the problem

heady sleet
#

I know

valid turtle
deft grail
heady sleet
#

I have my subject!

deft grail
# heady sleet

if your talking about modding "bean", then dont.
modding isnt allowed in this server lol

valid turtle
deft grail
#

just make your own game

#

not sure what the point of modding games is anyway

#

some random games

valid turtle
#

But a bool dosent have a value. Its only true or false no?

deft grail
#

your finding and setting a script, not a bool

valid turtle
#

because we were trying to fix that I couldnt stop getting either 0 points or 1 point even if the bird is ded

#

and I tried that with a bool

deft grail
#

yes because you were trying to get the bool from thin air

#

you need to get it from your actual instance of your script

#

which is what you did by making a variable and setting its value to an instance of the script

valid turtle
#

Okay but this:

SchloppyLebt = GameObject.Find("Schloppy").GetComponent<SChloppyScript>();
#

isnt reference the bool?

deft grail
#

its referencing the script

valid turtle
#

yes

deft grail
#

to reference the bool directly itself

valid turtle
#

OHHH

deft grail
#

but if you do it once in Start that wont help anyway

valid turtle
#

Sorry I cant read

#

I forgot the beginning part of SchloppyLebt

#

so I was like

#

how are we getting a value for the bool if we arent talking about the bool anywhere

deft grail
deft grail
#

only in the if statement

valid turtle
#

But SchloppyLebt is the bool no?

public bool SchloppyLebt = true;
#

So if we do this:

        SchloppyLebt = GameObject.Find("Schloppy").GetComponent<SChloppyScript>();

we are talking to (or about) the bool

deft grail
#

you can name it whatever you want

#

it wont change a thing

valid turtle
#

okay now I understand nothing again

#

One sec

#

I might understand it

deft grail
valid turtle
#

So the problem started here:

 if (collision.gameObject && SchloppyLebt.SchloppyLebt == true)
        {
            logic.addScore(1);
        }

I wasnt using
SchloppyLebt.SchloppyLebt

But instead SChloppyScript.SchloppyLebt

So we made this:

SchloppyLebt = GameObject.Find("Schloppy").GetComponent<SChloppyScript>();

But if this 2nd line of code dosent have anything to do with the bool, why did the 1st line now know what to do?

deft grail
valid turtle
#

right

#

and?

#

we need the 2nd line so that what happens?

#

Im so stupid ngl

deft grail
#

so SchloppyLebt = GameObject.Find("Schloppy").GetComponent<SChloppyScript>(); or public SChloppyScript SchloppyLebt;
have nothing to do with your bool

#

these just reference the SCRIPT

valid turtle
#

yes

#

So if I ever do something like this agian, I would need both

public SChloppyScript SchloppyLebt;

// and

        SchloppyLebt = GameObject.Find("Schloppy").GetComponent<SChloppyScript>();

to make points only appear when the character is alive

because the public line isnt enough of a reference

deft grail
#

what you can also do is

valid turtle
#

in the inspector it is only a checkbox

deft grail
#
//In your SChloppyScript

public static SChloppyScript Instance;

void Awake()
{
  Instance = this;
}

and in your trigger script do SChloppyScript.Instance.SchloppyLebt == true

deft grail
deft grail
valid turtle
#

AHhh

#

okok

deft grail
#

or what you did with a Find

#

or assign the variable when you Instantiate the pipe

valid turtle
#

okay

#

So just for future proofing

#

why is finding not good?

deft grail
#

and because theres better ways of assigning a variable

valid turtle
#

okay

deft grail
#

the best one would be when instantiating it

valid turtle
#

But thats impossible if I like make something, then decide to add something else, then I have to delete the first thing and remake it so the 2nd things works perfectly?

deft grail
#

add what

#

depends what your adding and changing?

#

idk

valid turtle
#

I wanted to create a FlappyBird clone

So I made the basic game with jumping, pipes and game over

To make the pipes I make a prefab so it dosent infinetly creates pipes

Then after Im basically done I want to add a Score system.

But to not use find I would need to delete the prefab and recode the pipes so I could properly add the scoresystem to avoid find

deft grail
#

you just need to change the way you reference

valid turtle
#

because you said I cant reference to a prefab

deft grail
#

a prefab cant reference scene objects yeah

deft grail
valid turtle
#

Okay

#

I think I will just leave this how it is. I think I half understood what you kindly tried to explain to my stupid monkey brain.

We fixed it and I can move on to the next addition for the game haha

deft grail
#

for your first or even second or even 10th project if they are all small/prototypes
then bad code doesnt really matter

valid turtle
#

Using the bool value: The boolean SchloppyLebt.SchloppyLebt is part of the SChloppyScript. If you don’t assign SchloppyLebt to the right object using GameObject.Find and GetComponent, the script wouldn’t know which instance of the SChloppyScript you're referring to, making it impossible to check its SchloppyLebt value.

This is what ChatGPT spat out.

Now I get it

deft grail
valid turtle
#

Like how does it know which component to fetch if we didnt specify

deft grail
valid turtle
#

oh so

deft grail
#

then it errors

valid turtle
#

The two lines of code would only work togehter

#

never alone

deft grail
#

thats it

#

or if you use ONLY the 2nd line also, would work

valid turtle
#

because it only knows to fetch .schloppylebt by needing it for the point adding

valid turtle
deft grail
#

by the 2nd line you mean the one with Find correct?

#

thats what i mean at least

valid turtle
#
if (collision.gameObject && SchloppyLebt.SchloppyLebt == true)
        {
            logic.addScore(1);
        }
deft grail
valid turtle
#

OHHHH
Okay

#

My god

#

How do you even have the energy to explain this to me

#

wow man

deft grail
valid turtle
#

XD

graceful osprey
#

is there any solution for pink items?

deft grail
valid turtle
#
GameObject.Find("...").GetComponent<TheScript>().SchloppyLebt == true

This line of code is basically cut in half in my code.

Thats the thing I didnt understand.

deft grail
valid turtle
#

You are talking the language of the gods xD

#

"it" and "it"

#

one last thing