#💻┃code-beginner

1 messages · Page 2 of 1

wintry quarry
#

Do you understand this line of code?
var cardIcon = obj.transform.Find("cardImage").GetComponent<Image>();

#

think about how you'd change this code to find the image component directly on obj instead of on a child object

#

you can do it

acoustic arch
#

just getcomponent image

#

instead of

#

Find(cardImage)

#

obj.GetComponent<Image> ?

wintry quarry
#

yes

#

though if it were me, poersonally

#

I would replace:
public GameObject InventoryCard; with public Image InventoryCard;

acoustic arch
#

then i can just put in the blank

wintry quarry
#

then your code can just be

Image cardIcon = Instantiate(InventoryCard, CardContent);
cardIcon.sprite = card.cardImage;```
acoustic arch
#

yeah

#

im only making this to practice inventory/lists so ill try it

acoustic arch
wintry quarry
#

Image IS an Object

#

what error are you getting

acoustic arch
#

Severity Code Description Project File Line Suppression State
Error CS0311 The type 'UnityEngine.UIElements.Image' cannot be used as type parameter 'T' in the generic type or method 'Object.Instantiate<T>(T, Transform)'. There is no implicit reference conversion from 'UnityEngine.UIElements.Image' to 'UnityEngine.Object'. Assembly-CSharp D:\Unity\Projects\ClickerGame\Assets\Scripts\CardInventoryManager.cs 30 Active

#

i copy and pasted

#

obviously

wintry quarry
#

that's the wrong one

#

using UnityEngine.UI; is correct

acoustic arch
#

my IDE keeps adding them

wintry quarry
#

you did using UnityEngine.UIElements;

acoustic arch
#

well now i have a new error which is technically one step in hopefully the right way

acoustic arch
wintry quarry
acoustic arch
#

oh wow im slow

#

i was wrong and it uses sprites not images

#

so i switched everything over

#

Sprite cardIcon = Instantiate(InventoryCard, CardContent); cardIcon = card.cardImage;

wintry quarry
#

that's not right

#

Sprite is the asset

acoustic arch
#

no?

wintry quarry
#

Image is the thing that displays it

#

Unless you mean a SpriteRenderer

acoustic arch
#

using UnityEngine;
[CreateAssetMenu]
public class CommonCard : ScriptableObject
{
public int cardID;
public Sprite cardImage;
public int cardRating;

wintry quarry
#

yes

acoustic arch
#

is the actual card

wintry quarry
#

the Image displays the sprite

#

see here

#

you have an Image component

#

it has a field for a sprite in it

#

the ScriptableObject has a reference to the sprite you want to display in the Image component

acoustic arch
#

it wouldnt lemme put anything on the image for public Image InventoryCard;

wintry quarry
#

this is the thing that goes there

acoustic arch
#

ohh ok i get it

#

but why cant i put anything in the public Image InventoryCard; ?

wintry quarry
#

you can

acoustic arch
#

it only has

#

none

wintry quarry
#

you can put an object that has an Image component there

#

such as your card prefab

acoustic arch
#

ohh

#

WHOA its working!

#

thanks

acoustic arch
#

im thinking its cause the listitems method is inside when i click the inventory button

wintry quarry
#

Are you ever destroying them?

#

A better approach usually is to just reuse the objects

acoustic arch
#

can i just have the prefabs be destroyed when its closed out

fading slate
#

I get no errors in the Vs Studio but when i run it in unity i get ArgumentNullException: Value cannot be null.
Parameter name: _unity_self

this is the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Ball : MonoBehaviour
{
public Rigidbody2D rb2d;
public float maxInitialAngle = 0.67f;
public float moveSpeed = 1f;

private void Start()
{
    InitialPush();  
}

private void InitialPush()
{
    Vector2 dir = Vector2.left;
    dir.y = Random.Range(-maxInitialAngle, maxInitialAngle);
    rb2d.velocity = dir * moveSpeed;
}

private void OnTriggerEnter2D(Collider2D collision)
{
    Debug.Log("ladida");
}

}

uncut dune
#

double click it

#

and see what line it puts u in

eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

wintry quarry
#

and share your full error message @fading slate

#

not that errors at runtime are normal it just means it's a runtime error, not a compile error.

#

VS cannot detect runtime errors

fading slate
wintry quarry
#

hatebin was meant for the code itself but

uncut dune
wintry quarry
#

this looks like an error in the unity editor/inspector, not in your code @fading slate

fading slate
#

i have it assigned to the ball

#

i am trying to create a scorezone for pong

uncut dune
#

just print screen it

#

its okay

fading slate
#

sorry i am a bit confused again so i see the error into the console

uncut dune
#

double click the error

fading slate
#

and i double click it but nothing happens

wintry quarry
#

it's from internal unity editor code

#

double clicking it won't help you

uncut dune
wintry quarry
#

and it has nothing to do with the script you shared

uncut dune
#

exactly

#

ur code is fine

#

when does the error happen

#

and how manny of them

#

maybe make a vid showing?

fading slate
#

alright i will make one now, sorry if i dont understand things properly also

languid spire
#

it's a UIToolkit error, closing the project and opening it again will fix it

uncut dune
#

sometimes just selecting other gameobject on the scene fixes them

languid spire
#

it's a serialized property error, which means a rebuild of the AssetDatabase

#

which close/open will do

uncut dune
#

guys I need some help again

#

this error

#

I thought I had fixed it

#
 foreach(GameObject enemies in enemiesToBeSpawned.Keys)
                    {
                        currentNumberOfEnemiesToSpawn = allRooms[CurrentRoomType].NumberOfEnemiesAtATime;
                        if(currentNumberOfEnemiesToSpawn > 0)
                        {
                            while(enemiesToBeSpawned[enemies] > 0 && currentNumberOfEnemiesToSpawn > 0)
                            {
                                GameObject colliderCheck = Instantiate(Spawner, roomPos + new Vector2(Random.Range(-rooms.Point.x, rooms.Point.x), Random.Range(-rooms.Point.y, rooms.Point.y)), Quaternion.identity);
                                ColliderCheck colliderStats = colliderCheck.GetComponent<ColliderCheck>();
                                colliderStats.enemyType = enemies.GetComponent<EnemyHealth>().EnemyType + 1;
                                colliderStats.enemy = enemies;
                                enemiesToBeSpawned[enemies] -= 1;
                                currentNumberOfEnemiesToSpawn -= 1;
                            }
                            if(enemiesToBeSpawned[enemies] == 0)
                            {
                                EnemiesToBeDeleted.Add(enemies);
                            }

                        }
                    }

#

in this foreach

#

Cant I change and item in a foreach

#

using a dic

languid spire
#

yes you can but you need to use KeyValuePair not .Keys

uncut dune
#

this?

#

I cant change it

languid spire
#

no

uncut dune
#

where

languid spire
#

foreach(KeyValuePair<GameObject,int> enemies in enemiesToBeSpawned)
then you can use enemies.Key for the GameObject
and enemies.Value for the int

uncut dune
#

I dont quite understand it

languid spire
#

woah, wait, that's not gonna work because the int in enemies.Value is not the same int as in the dictionary

#

A KeyValuePair is one entry from the dictionary

#

with both the Key and the Value

pearl cloud
#

Has anyone ripped this shills base code and uploaded it to the dark web yet? Asking for comrades…

river roost
languid spire
#

@uncut dune Try this

using System.Linq;
...
        Dictionary<GameObject, int> gos = new Dictionary<GameObject, int>();
        gos.Add(gameObject, 0);
...
        foreach (GameObject go in gos.Keys.ToArray()) {
            gos[go]++;
        }
        Debug.Log(gos[gameObject]);
jovial pilot
#

Hey guys, i have a window gameobject. I wanna like rotate freely, example, moving the Z-Axis of the window from current position to value 74 smoothly. How do i do it? I have this code but this is not moving smoothly.

  windows[0].GetComponent<Rigidbody>().transform.localRotation = Quaternion.Lerp(Quaternion.Euler(0, 0, -64f), Quaternion.Euler(0, 0, 74f), timeCount);
timeCount += Time.deltaTime * 0.22f;
languid spire
#

presumably that code is in a Coroutine

jovial pilot
languid spire
#

post the complete Update method, a screen shot will do

languid spire
jovial pilot
#

Tried

#

Still the same

languid spire
#

Can you make a vid of whats happening, your code looks fine, a bit odd but it should work ok

jovial pilot
languid spire
#

no

jovial pilot
#

Yea scratches head

#

i don't know

#

one sec lemme restart unity

languid spire
#

show the inspector of the object you are rotating

hot sun
#

coroutine not working

#

is there any problem in code?

jovial pilot
languid spire
#

Floor to int will always return 0

hot sun
languid spire
#

Look at your FloorToInt call it can only result in 0

languid spire
queen adder
#

i dont wanna add this check for everytime i press an input 🥹

hot sun
languid spire
#

I've given you your answer!

jovial pilot
hot sun
jovial pilot
#

.localRotation to .rotation?

languid spire
languid spire
uncut dune
#

why dont u just do the normal multiplication?

jovial pilot
languid spire
#

define 'doesn't work' exactly

jovial pilot
#

It will be like stop to the 74 in a sudden

hot sun
languid spire
#

of course not, that is not what you have programmed

#

also not what you asked

languid spire
uncut dune
#

couldnt u just do it in start method

#

or maybe instead of using a loop just put it in update

hot sun
#

i want the score to just constantly keep increasing

uncut dune
#

so it will update every frame

uncut dune
jovial pilot
languid spire
#

just make score a float instead of an int

hot sun
#

yes

uncut dune
uncut dune
# hot sun yes

can u paste the code here and I'll show u what I would do?

hot sun
#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class ScoreManager : MonoBehaviour
{
public TextMeshProUGUI scoreText;
int score = 0;
public static ScoreManager instance;

// Rate at which the score increases per second
public float scoreIncreaseRate = 1.0f;

// Start is called before the first frame update
void Start()
{
    scoreText.text = score.ToString() + " POINTS";

    // Start the score increase coroutine
    StartCoroutine(IncreaseScoreOverTime());
}

// Coroutine to increase the score over time
IEnumerator IncreaseScoreOverTime()
{
    while (true) // Infinite loop to keep increasing the score
    {
        // Increment the score based on the rate and time elapsed
        score += Mathf.FloorToInt(scoreIncreaseRate * Time.deltaTime);
        scoreText.text = score.ToString() + " POINTS";

        yield return null; // Wait for the next frame
    }
}

}

languid spire
uncut dune
#
    void Update()
    {
       score += scoreIncreaseRate * Time.deltaTime;
       scoreText.text = score.ToString("00") + " POINTS";
     }
#

also score should be float

#

so

#

float score = 0;

jovial pilot
neon stirrup
#

can simebody explain to me how to make movemnt for players in 2d platformers

languid spire
neon stirrup
#

hello?

jovial pilot
# languid spire of course, like I said

Hmm.. okay.

 timeCount += Time.deltaTime;
``` i changed to this. Its moving as it is but it won't stop gradually. Not sure if its my code or im doing something wrong
languid spire
#

you are not thinking or looking at what I said

rich adder
languid spire
#
float step = 0.22f;
void Update()
    {
        transform.rotation = Quaternion.Slerp(from.rotation, to.rotation, timeCount);
        timeCount = timeCount + Time.deltaTime*step;
        if (timeCount > 0.5f) // After halfway
           step += 0.05f; //slow down
    }
#

as step gets bigger so the rotation slows down

jovial pilot
#

I'll try on this.

#

One moment

jovial pilot
#

🙏

queen adder
#

is there a builtin HexToCOlor method?

queen adder
#

that's what im using too, but it is quite ugly to write for me

#

imma write my own that just return a color ig

valid magnet
#

Hi everyone 👋 - I am wondering what is the correct way of building a menu system for a game - is it to have a 'scene' for each step in the setup of a game? And is this best to build entirely with UI Builder? Thanks in advance

valid magnet
#

Ok thanks

#

was more from a game architecture angle but I will ask in there

queen adder
#

UI builder! Sounds like a cool stuff i cant have 🥹

languid spire
queen adder
#

save me the stress ig, knowing me, id force it to work even though i have other ways to solve a problem

languid spire
#

Even Unity can't get it to work correctly, hence all the Editor UIToolkit errors we keep seeing people posting

queen adder
#

oh i see, so it was also the UI toolkit, yea im quite aware how frequent someone got problems with it UnityChanOops

lavish ginkgo
#

how do i close a demo

#

demoscene

bleak wadi
#

How to name the base class for Projectile and Laser?

languid spire
languid spire
lavish ginkgo
bleak wadi
languid spire
#

It's better than CouldBeAnythingThatComesOutOfTheEndOfAWeaponWhenFired

languid spire
ashen ferry
#

im trying to draw ray and freezing time to see why the hell it misses the thing I click on if planet itself is moving but ray clearly intersects box collider first before sphere one so now im confused https://hatebin.com/zbtorzaukh

rich adder
#

oh my god this switch lol

rich adder
languid spire
#

That Debug.Log appears to be coming from MouseInput not ClickedOnScreen
The MouseInput code you posted does not have a Debug.Log

ashen ferry
#

whats up with switch and ye if it hits box collider u see in vid it would print BuildingSlotRoot name

#

but it prints earthroot in console u can see

#

that should happen if that ray hits sphere collider on earth only

rich adder
ashen ferry
#

I moved out related code

#

before posting

rich adder
#

those siizes looksus

ashen ferry
#

into its own method but its same stuff

#

white box is bounding box I think unrelated

#

actually nvm let me see wtf is that white box lol

#

oh

#

thats ui

rich adder
#

so where is the box collider at

ashen ferry
#

not ui

#

I mean camera

#

viewport

rich adder
#

btw if you wanna pause to debug is better to use
Debug.Break() than timescale (it doesn't effect other scripts from executing)

ashen ferry
#

didnt knew ty

#

and combined with earth sphere collider

#

it extrudes and ray intersects it

rich adder
ashen ferry
#

relative to earth yea

quaint crow
#

is there any teenagers that want to talk about coding with me im 13

#

and i want to lurn how to code

ashen ferry
#

its kinda off topic tho im more interested in maybe my ray draw is just wrong cause how can it just ignore my collider

#

I need to compensate click to the side to actually hit it lol

rich adder
rich adder
ashen ferry
#

its a tool to debug

#

so I draw the actual ray

rich adder
#

yes but it doesn't stop at colliders

quaint crow
ashen ferry
#

yea so u see

#

I have the real ray running in that code I posted yes

#

and just after that I draw a line using that ray origin and its direction

#

so I can just assume my real ray is going through exactly that line

rich adder
#

you should draw the ray from Ray.origin to rayhit.point

ashen ferry
#

aa lemme see

rich adder
#

believe that would be a Debug.DrawLine

quaint crow
rich adder
#

if its not hitting the square, the collider might be moving (maybe you have non-uniform scale somewhere and rotating skewed)
@ashen ferry

rich adder
quaint crow
ashen ferry
#

yea so my ray bro actually just hits air kekW

quaint crow
quaint crow
languid spire
#

Look under Resources in the pinned messages

rich adder
#

what is scale Root Planet or w/e is called

ashen ferry
#

1 its quite nested with varying scales tho but wtf do I do if that matters

#

theres no apply transforms or anything like in blender

rich adder
#

it causes skewing on rotation

#

eg of non-uniform

0.3 | 0.2 | 0.3

ashen ferry
#

oh nah

#

its aight tho nevermind one of those bugs where im getting cancer trying to figure out and 2 days later it will be something incredibly simple

rich adder
remote lynx
#
        GameObject prefab = Resources.Load<GameObject>("Prefabs/PlayerPrefab");
        player = Instantiate(prefab);
```this gives me "the object you are trying to instantiate is null but there is a prefab named "PlayerPrefab" on the assets/prefabs folder
remote lynx
#

thank you

summer gust
#

Hey guys, I'm having some trouble with trying to solve fast diagonal movement with an analogue stick

The solution I'm seeing online is:

if (input.magnitude > 1)
input.Normalize();
or using Vector3.ClampMagnitude

This works well with keeping my character from going over the speed limit that I've set, but if I try to adjust the input factor and pass in 0.5,0.5 the diagonal magnitude will still be around 0.7 and it moves faster diagonally because of this

I can't just normalise the input always because the magnitude then clamps to 0 or 1

Any help would be appreciated, thanks. I seem to be missing something, as everyone online is happy with the initial solution but I'm still having issues

quaint crow
#

I need Friends really badly and i want to make a game so im 13 my name is Christopher and I use unity if you want to make a game with me reply

fringe pollen
#

man why the commands never work for me
!collab

eternal falconBOT
fringe pollen
#

there we go

toxic void
#

Hi, I want my 2d sprite to rotate to face left, up, right, down through code, but I don't want to learn quaternions for that, which parameter do I need to change to control the rotation on the Z axis?

fluid remnant
languid spire
#

or you can multiply the Quaternion by the Vector3 of the direction you want

toxic void
fluid remnant
late burrow
#

how to store list of lists

#

it enforces every list to be of same type but i want different types

queen adder
languid spire
#

List<List<object>>

late burrow
languid spire
#

no

#

everything in C# is basically an object

late burrow
#

and how would dictionary work

#

i think its forced to have 2 types i want more

polar acorn
#

object can hold any variable

#

Can't really do much with it other than just pass the reference around though

late burrow
#

o right

languid spire
#

you could even do
List<object>
and just fill is with anything you want

late burrow
#

yeah thats what im trying rn

#

i think thats best solution

languid spire
#

List<List<object>> is better

#

if all your storing is Lists

subtle hedge
#

how can i take the point of a raycast even if it didn't hit anything

languid spire
#

origin + origin.normalized * distance

subtle hedge
#
 Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
 if(Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity))
 {
     Vector3 pos = hit.point - transform.position;
     transform.rotation = Quaternion.LookRotation(new Vector3(pos.x, 0, pos.z), Vector3.up);
 }```in my case how do i implement it
languid spire
#

in your case you dont

ashen ferry
#

whats the legit use case for List<List<object>> if fr like wut

languid spire
subtle hedge
ashen ferry
#

yea and what u gonna do when u want to do something with certain list

languid spire
languid spire
oblique torrent
#
        int directions[] = Board.Squares[i].pieceColor == Piece.LightColor ? new int[] { 7, 8, 9 } : new int[] { -7, -8, -9 };

cannot convert from type int[] to int
used this exact line of code in another project and it was working, whats the problem here

#

is it cuz im using a newer version of c# or smt

languid spire
#

Exact?
int [] directions

oblique torrent
#

oh your right

#

mb

#

thanks

#

didnt notice that

sharp abyss
last grove
#

whats the best way to rotate a quaternion on one axis without having to change any of the other values? orientation.rotation = Quaternion.AngleAxis(yRotation, orientation.up);This is what I have so far but it's just causing my capsule to spin violently

#

This is for a camera script, I will post the full script if asked

uncut dune
#

how to find the component of an inactive object with a tag?

fluid remnant
uncut dune
#

the there is already

#

other gameobjects with the same component

#

I want one with a specific tag

#

I cant do that

#

cuz that would be calling the gameobject wouldnt it

fluid remnant
#

yes

#

why is the object disabled?

#

just disable the components

#

this way you can use Tag find

uncut dune
#

I cant just

#

disable the slider component cuz the object would be still showing

fluid remnant
polar acorn
uncut dune
polar acorn
uncut dune
polar acorn
uncut dune
polar acorn
#

In that case, have the thing that spawns the prefab with a reference that you drag in, and then set the variable after you spawn the prefab

uncut dune
#

good idea

wary sable
#

Hello, I am currently trying to make enemy pathfinding for my game. I have a basic navmesh system working, but I wanted to make it better with a "predictive" system. I followed a Llama Academy tutorial for creating such a system, but when I attempt to run it I recieve an AABB error.

Heres my code:
https://pastebin.com/f3tfMSvU

Here's the tutorial:

video https://www.youtube.com/watch?v=1Jkg8cKLsC0
github repo https://github.com/llamacademy/ai-series-part-44/blob/3779343025f1b5218d35b40427a2adc74eae8f69/Assets/Scripts/AI/EnemyMovement.cs#L4

Here's a screenshot of my errors:

#

I should note that when I just run: agent.SetDestination(victim.transform.position); there are no errors and the pathing works just fine.
victim referring to a class put onto the player (or any desired G.O.)
said victim class also runs a script called PosSpy shown in the pastebin below;
https://pastebin.com/UyRyVFiT

uncut dune
#

make targetpos

#

a Transform

#

and then pass the transform

#

targetPos = victim.transform;

#

like this

#

agent.SetDestination(targetPos.position);

#

try this

#

Ive had a similar problem and this solved it but Im not sure why was it, maybe someone else can answer

wary sable
#

the only thing is that targetPos already seems to be a Vector3

Vector3 targetDirection = (targetPos - transform.position).normalized;
Vector3 playerDirection = (victim.transform.position - transform.position).normalized;

float dot = Vector3.Dot(playerDirection, targetDirection);
if(dot < PredictionThreshold) {
  targetPos = victim.transform.position;
}

agent.SetDestination(targetPos);```
#

since it is defined as a vector3 type, the script wouldn't compile if it didn't contain a vector3 value

#

if I try to define targetPos as a Transform, then the original definition for targetPos does not work, since you are passing in a Vector3 at the start.

sage elm
#

Hey, guys!
All very well?

I recently started learning Unity and I'm trying to make a jump function using the Input System

But I'm having problems, I reviewed the code and input mapping, but it doesn't work, can anyone help me please?

#
private void OnEnable()
{
    playerActionsAsset.Player.Jump.started += DoJump;
    move = playerActionsAsset.Player.Move;
    playerActionsAsset.Player.Enable();
}

private void OnDisable()
{
    playerActionsAsset.Player.Jump.started -= DoJump;
    playerActionsAsset.Player.Disable();
}

private void DoJump(InputAction.CallbackContext obj)
{
    if(IsGrounded())
    {
        forceDirection += Vector3.up * jumpForce;
    }
}

private bool IsGrounded()
{
    Ray ray = new Ray(this.transform.position + Vector3.up * 0.25f, Vector3.down);
    if (Physics.Raycast(ray, out RaycastHit hit, 0.3f))
        return true;
    else
        return false; 
}
oblique torrent
#

why am i getting an error when trying to compare a Color32 with another Color32 using ==

#

nvm i just used Equals() instead

wintry quarry
graceful spruce
#

Hey, I made it so when an enemy collides with player the enemy attacks the player and it works. But I want the enemy to attack the player multiple times instead of just once. Im using the oncollisionenter2d. How would i go about to make that happen?

covert matrix
#

Hi I'm currently trying to make a game with similar mechanics to pokemon. Would it be okay to ask for help in this channel or would it be better in some other channel/thread?

covert matrix
#

Mostly about code, and maybe how to attach them to the game objects in unity

graceful spruce
rich adder
graceful spruce
#

Im not on pc so I cant check if that works or not

rich adder
#

so they should always make contact

graceful spruce
#

Okay I'll try the trigger thingy tomorrow and hope it will work, another question is if i want it to deal damage every like 1 sec or 0.5s how do i do that

rich adder
covert matrix
#

I'm currently trying to transition between the overworld (where the player moves the character and interacts with npcs), and the conversation (which is the battle in pokemon) on the condition that the player presses the interact button while colliding with an npc. So far when the player interacts with the npc, a dialogue box appears. Then I'd like to move back from the conversation to the overworld when they pick the last correct option.

So question is how to make those two transitions? any help is appreciated

rich adder
#

show a dialogue gameobject you can change dynamically, depending the npc or w/e

covert matrix
#

the convo part is a multiple choice with a button that does something different for each choice, would that still apply?

rich adder
#

you can re-use the same button for different method/scripts passing the reference around,
Adding/Removing 'listeners'

covert matrix
#

hmm sorry im a complete beginner, could you explain further on how to do that?

stiff obsidian
#

I have an issue. Say I need different tutorial images for a different scene. If the player is still holding down a key from the previous scene (because my game doesn't need any loading screens, so that is bound to happen), the tutorial is skipped as the game detects a keypress and thinks the player pressed a key. How can I circumvent that?

https://gdl.space/ehibopazaz.cpp

stiff obsidian
#

Do you think I'd be able to ignore the input all entirely? Or is a cooldown the best solution?

rich adder
covert matrix
#

thanks for the help, ill try to figure that out

rich adder
stiff obsidian
rich adder
#

or just if(Input.anyKeyDown && !Input.GetKeyDown(myKeyCodeVar)) //do stuff;

#

kinda ugly tho might create other issues, probably better to approach what you're doing differently

west stone
#

Help, Unity crashes when switching from game to scene view (randomly).
I'm on Windows, using AMD ryzen 9, Radeon RX 6950

a fatal error in the mono runtime or one of the native libraries 
used by your application.```
hoary citrus
west stone
#

My b, thanks!

neat bay
#

does anybody know how to fix this?

#

I literally haven't touched my project since last time and it was working fine

#

just woke up to this

ivory bobcat
#

Press clear?

neat bay
#

How does that fix the error

ivory bobcat
#

Unless you've done something this could be a false positive and clear or resetting the editor may quickly fix.

neat bay
#

Nope, there's definitely an error

#

Currently its causing my game object in my inspector to look like this

ivory bobcat
#

Well, it's got to do with reflection and the mesh simplification controller, good luck.

neat bay
#

Lovely

oblique torrent
ivory bobcat
#

Make sure they're the same type - could be referring to Unity's and another.

#

Or maybe color 32 doesn't have an overload for the equality operator

wintry quarry
jovial pilot
#

Hi guys, i have a question on rotation. I have an object where i am rotating the Z axis. How do i have the mid point or 75% of the arc/rotation marked as ?? I'll be glad if anyone can help me out. Thank you 🙏

I am using values.
Example A val = 255, B val = 50

rich adder
jovial pilot
#

sorry, you mean, quaternion lerp?

north kiln
#

I am unsure how you don't get the shorter angle, there must be some third variable to indicate why you want that particular direction

obtuse lodge
#

im attempting to trying to produce a cube on a specific face of another, then again on the cube created in the first action. does anyone have any ideas?

#

with the new starting point always being the end of the most recent iteration, the length and thickness always being the same based on the text put in the given field, and the number of iterations based on the number of letters

#

it feels very complicated, and im sorry to ask so much

jovial pilot
north kiln
#

Quaternions are always interpolate the shortest part. Math.LerpAngle is designed to do the shortest lerp in euler angles (0->360), and normal Math.Lerp just interpolates between two numbers, and knows nothing about context

jovial pilot
#

anyway, why is it returning in decimal when i do this Debug.Log(gameObject.transform.rotation.z);? Is it in radian?

jovial pilot
#

ok tq

jovial pilot
north kiln
#

Read the note on that very page

jovial pilot
north kiln
#

Yes, I understand

#

The note is talking about angles read in code differing from those in the inspector

jovial pilot
#

and what i dont get it is, inspector is giving different value as what i debug

north kiln
#

Did you read the note?

jovial pilot
#

yes

ivory bobcat
north kiln
#

Then what's confusing about it? The inspector values are user authored. The values returned from eulerAngles are derived, and go through a transformation

#

When scene as a complete rotation with all angles, the result is the same

#

but individual angles are meaningless without the full context of the rotation

jovial pilot
ivory bobcat
#

They're both the same angle interpreted differently

north kiln
#

Depends completely on your implementation, I give suggestions in the note

jovial pilot
#

Alright thanks guys 🙂

maiden minnow
#

tryna work with the new input system, got this
Assets\Scripts\MouseManager.cs(118,25): error CS0246: The type or namespace name 'InputAction' could not be found (are you missing a using directive or an assembly reference?)

#

the void with the error:

private void OnLook(InputAction.CallbackContext ctx)
    {
        if (ctx.performed)
        {
            _input = ctx.ReadValue<Vector2>();
            _isGamepad = ctx.control.device is Gamepad;
        }
    }```
slender nymph
#

are you missing a using directive or an assembly reference?

maiden minnow
#

like Using UnityEngine.something

north kiln
#

Do you understand it though 🤔

maiden minnow
#

some reference is missing. But I'm asking, what reference is missing

slender nymph
#

use the quick actions in your IDE to add the correct using directive like vertx's link shows

maiden minnow
#

k works now

stoic pike
#

https://gdl.space/murosubebe.cpp
I wrote this is code as a system to equip different skins inside my game, but the value isnt being saved across playthroughs
Anyone know why

slender nymph
#

you're not actually using the value you get from PlayerPrefs. you call PlayerPrefs.GetInt but don't store the value anywhere

stoic pike
#

doesnt player prefs set int store the value?

slender nymph
#

i mean store it in your code to use in your code. GetInt returns the int, but you don't put that returned int into a variable

stoic pike
#

letsgo it worked thx

vestal valve
#

Guys, How to destroy a gameobject when it is triggered?

slender nymph
#

Destroy(gameObject)

vestal valve
#

Simple as that ?

eternal needle
#

that likely will not be what you want to do exactly but 🤷‍♂️ you havent really described what you're doing

vestal valve
slender nymph
#

what have you done to make sure that OnTriggerEnter is actually being called?

queen adder
#

can we add another option here ?

vestal valve
#

Oh my god,
wait a sec
Should I place the function in "Update"?

languid spire
#

no @vestal valve

queen adder
#

menu items maybe?

#

can we add another option in here?

#

test

vestal valve
slender nymph
languid spire
rich gazelle
rich gazelle
#

Easier for us to help

vestal valve
slender nymph
#

have you tried any debug.logs? have you used breakpoints? or have you done nothing and already run out of ideas?

vestal valve
#

I'm sorry, there was no mistake in coding, its my eyes, I just checked for "is trigger" toggle.
But never looked out the "collider"

dark berry
main karma
#

hello, I want to create a platform system where I can specify the number of instructions the platform needs to make, and them configure and set each one from the editor w start/stop time, also the action between rotation or movement.
how do I get the editor to update dynamically with the number of instructions so I can set all of them (without adding a different script on top and modifying that one)

#

I was thinking of making the basic movements and their configuration and then having a manager script specify the script count for each platform and then configure them from there

queen adder
#

So uhhh, I just started with code, went to edit it, and I need to open it with something, is there a specific application I can use that's made for this stuff?

main karma
#

or visual studio code

queen adder
main karma
#

I use visual studio

slender nymph
#

make sure you configure it too !IDE 👇

eternal falconBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

barren vapor
main karma
#

what about notepad++ tho?

barren vapor
#

I only use it for small scripted games on a computer

main karma
#

I mean it's the best I could do on my school computer

honest haven
#

can i change what way a slider fills. i.e would like the start to be top right

frigid turtle
#

Or scaling it negatively if you want to "mirror" it

honest haven
vestal valve
#

hey a quick question
If I use "Instantiate", The game object gets spawned once. Is there any shortcut to spawn multiple times or Should I type the code again.
(Excluding the loop functions)

frigid turtle
vestal valve
#

ok

silent valley
#

Hi. I am trying to find a way to add +1 to my battery counter when i collect a battery. I cant figure it out in a clean way of code. I've managed to get it to work by making a separate script that has a void start +1 that will enable once i collect the battery hence giving me +1 but i really dont like this method. any help please

slender nymph
silent valley
#

I played around with that for hours and could not get it to work.

#

i assume I add the flashlight script to it since that holds the value of batteries, then what. thats where i get lost

slender nymph
#

then you can create a method on the desired class that you call from the interaction event and that can increase the count by 1

dusk minnow
#

i saved my code then this somehow appeared

slender nymph
#

that's a build error. if you weren't trying to build then clear the console and move on

#

you can even restart the editor if it bothers you that much

dusk minnow
#

it doesnt let me start bcs of error and it keeps appearing

silent valley
slender nymph
#

both . . .
surely you know what a method is, yes?

silent valley
#

update/start etc right?

slender nymph
slender nymph
dusk minnow
slender nymph
#

did you restart the editor?

vestal valve
#

How to use "and" function in C#
Does "and", "or" exists ?

dusk minnow
#

yes.

slender nymph
silent valley
#

So I'd make a new method, and then call upon that method I made to increase it by 1 when I press my interaction button

slender nymph
#

yes

silent valley
#

gotcha. Thank you. Makes sense now

dusk minnow
slender nymph
#

okay well this is a code channel

dusk minnow
#

in a scene i could somehow not save it bcs acces was refused

#

ok where do i ask this then

slender nymph
#

perhaps your install is fucked. or you may need to delete your Library folder. i have no idea, i'm just a programmer

vital tangle
#

hey i wanna ask a simple thing

#

what type of string it is

slender nymph
#

bcs acces was refused
well that sounds like an OS permissions issue

vital tangle
#

\x11LLL\x00\x07\x01\x02\x01\x00\x10\x9f\x9d\xa7C\x01

#

it kinda seems like hex

#

but dunno how to decode

eternal needle
vital tangle
#

requires some processing which i am unaware of

#

tho its a string representing hex

eternal needle
#

UnityChanHuh I have absolutely no clue what you mean by that

ivory bobcat
#

Where did you get that string from and what're you trying to do with it?

eternal needle
#

That isnt binary, and L isnt hex

vital tangle
#

the final result should be a base64 string

#

and converting it to a normal utf-16 string it returns offline/online

ivory bobcat
#

Seems like an ascii escape character for byte

vital tangle
eternal needle
vital tangle
#

its a possibility if the final string is utf-8

#

all i need to know is what is this thing even i dont know myself

#

\x11LLL\x00\x07\x01\x02\x01\x00\x10\x9f\x9d\xa7C\x01

vital tangle
slender nymph
#

that's a link to a message in this channel, mate
read and answer the question

ivory bobcat
#

It's not programming

vital tangle
#

sad

slender nymph
#

probably intentionally ignoring the question because it isn't remotely unity related

vital tangle
#

for unity

#

that might explain

#

I am doing side by side tests with python as well

dusk minnow
slender nymph
slender nymph
remote lynx
#
using System;
using UnityEngine;
using UnityEngine.EventSystems;

public abstract class PlayerButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler {
    [SerializeField]
    public GameObject player = null;
    public bool held { get; private set; } = false;

    public void OnPointerDown(PointerEventData eventData) {
        OnPress();
        Debug.Log("press");
        held = true;
    }

    public void OnPointerUp(PointerEventData eventData) {
        Debug.Log("release");
        OnRelease();
        held = false;
    }

    public void Update() {
        Debug.Log("frame");
        if (held) {
            OnHeld();
        }
    }

    public abstract void OnPress();
    public abstract void OnRelease();

    public abstract void OnHeld();
}

Update just doesnt get called somehow OnPointerUp & OnPointerDown logs but it doesnt log "frame"

slender nymph
#

does the inheriting class happen to have its own Update method?

remote lynx
#

ohh

#

yeah it does

#

i get it now thanks

slender nymph
#

for anyone that may be seeing this and wants to know how to fix it: mark the base class's Update method as virtual and override in child classes and call base.Update in those overriden methods

left star
#

Does anyone know why camera spawns at foot level?

slender nymph
#

obligatory "use cinemachine"

rich gazelle
#

You might be following the character model's pivot point

#

I would usually use a separate look at point that is positioned at character model head.

slender nymph
#

yeah that object's pivot point is at its feet

#

just use cinemachine though

rich gazelle
# left star

Yeah definitely you following character model pivot point hahaha

left star
#

i can only put pivot on center

#

not like in the head

rich gazelle
#

Try creating a empty gameobject on the character, then position it on the head.

rich gazelle
#

And then have the script follow the empty gameobject

#

But like boxfriend said, I recommend cinemachine too hahahaha

left star
left star
#

can i implement the cinemachine in a start project?

rich gazelle
#

What you mean by start project?

#

Oh you mean beginner project? Yeah sure of course you can

#

There's a whole unity tutorial on how to use Cinemachine

#

but if since you already have a camera script you might as well continue unless you are interested in cinemachine

vestal valve
#

How to move a gameobject left and right continuously ?
The code I wrote is not working.

rich gazelle
north kiln
#

Update is a loop that is executed every frame

#

Your loop completes in one frame, teleporting the object

#

Also .x will never equal 5 exactly

near ridge
# vestal valve How to move a gameobject left and right continuously ? The code I wrote is not w...
lilac hemlock
#

Can someone help me out. How do I make an object to snap to the terrain during run time? For some reason, the object is half under the terrain.

https://hatebin.com/lnnvjpbskz

rich gazelle
lilac hemlock
rich gazelle
#

Yeah then the basic cube's pivot point is in the middle I believe

lilac hemlock
#

how do i fix that?

#

without fixing the model's pivot point

ivory bobcat
#

Maybe your offset is wrong

rich gazelle
left star
#

Why is he flying? lol

rich gazelle
rich gazelle
left star
lilac hemlock
#

with a cube it is okay

#

but it seems a lot of manual work for more complex models

rich gazelle
rich gazelle
# left star Why is he flying? lol

Question, is the character falling when it gets to that height or it is a fixed position kind of thing (like just in mid-air, zero movement)

#

Or rather, does your character have rigidbody and a collider?

#

I'm assuming you do cos there's charactercontroller

hot sun
#

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

public class Lives : MonoBehaviour
{
public RawImage image1 ;
public RawImage image2 ;
public RawImage image3 ;
public static Lives instance;
private int flag = 3;

private void Awake()
{
    instance = this;
}
// Start is called before the first frame update
void Start()
{
    image1.enabled = true;
    image2.enabled = true;
    image3.enabled = true;
}

// Update is called once per frame
public void Remove()
{
    if(flag == 3){
        image3.enabled = false;
        flag--;
    }
    else if(flag == 2){
        image2.enabled = false;
        flag--;
    }
    else if(flag == 1){
        image1.enabled = false;
        flag = 3;
    }
}

public void Enable(){
    image1.enabled = true;
    image2.enabled = true;
    image3.enabled = true;
}

}

lilac hemlock
#

okay, thanks

hot sun
#

its saying error in this code

#

🤔

slender nymph
#

did you forget to drag RawImage objects into the slots in the inspector?

rich gazelle
hot sun
slender nymph
# hot sun no

well either you have more than one instance of this object in the scene, or you are not correct

hot sun
left star
rich gazelle
hot sun
left star
slender nymph
hot sun
slender nymph
#

okay, that's entirely irrelevant to what i've said

hot sun
#

is this u r talking abt?

hot sun
hot sun
#

u were right

#

i copied the canvas multiple times for diferent purposes

#

but didnt remove the script

#

😓

#

working fine now👍

left star
queen adder
#

whenever u post a question make sure to give some resource to it, we cant blindly guess because there is sooo soo many things that can go wrong

rich gazelle
queen adder
# left star

try reducing ur skin width in character controller for start

#

make sure ur animations dont control your Y position

#

if those 2 didnt fix it, then you will have to show us your script for movement

rich gazelle
queen adder
#

also make sure ur box collider isnt oversized

queen adder
#

while in play mode

#

go to analysis, physics debugger and show those gizmos

rich gazelle
#

@left star I think it's this situation

left star
#

maybe this one

queen adder
#

check before you start your game, what is your Y

#

if its -something

#

then thats why it goes up

rich gazelle
# left star yeah

Yeap, adjust your character controller's position, height and stuff.

#

these 3 things

left star
rich gazelle
modest dust
#

Question, would an attempt to call .SetActive(true) on a GameObject which is already active, cause to call OnTriggerEnter2D again for anything already within the trigger radius?

rich gazelle
left star
#

yeah done

#

thxxx

#

now I think I need to add gravity? bc if I go over something, the character flies again

rich gazelle
rich gazelle
modest dust
rich gazelle
modest dust
#

Basically the attack range is done badly and is set to active each frame
An entity once calling Destroy, exits the trigger twice, then re-enters it and OnDestroy get's called after that

queen adder
#

or create a different collider in child that will have ontriggerexit to enable the trigger in parent

modest dust
#

Well, I only needed to know if OnTriggerEnter2D would be called again by doing so, as for the solution I'll just beat my team members until they change it so that .SetActive(true) won't be called each frame, so there's no need for anything fancy like that

languid spire
modest dust
queen adder
queen adder
modest dust
#

I did send these to them, just in this case it won't be necessary

regal totem
#

Heyo, had a question. I've got a simple moving char, no mesh so no footstep animation. Getting a lot of diff ways to go about. What would be a good suggested way player simple walk around the house to play footsteps correctly? Would be same floor etc, could expand on that later, just want core down.

#

I was dabbling with the players velocity and I wasn't sure if just to use a timer or

#

Would be first person (why no mesh) and the player would stay at the same speed ideally walking around.

zealous oxide
#

good afternoon friends, how do I Physics2D.Raycast diagonally? https://hastebin.com/share/iyihuxepez.csharp i've tried the following: var right = transform.TransformDirection(Vector3(1,-1,0)); for a diagonally right down angle but i dont think i'm doing it right

ivory bobcat
# regal totem Heyo, had a question. I've got a simple moving char, no mesh so no footstep anim...

Best to lookup tutorials to see what fits your needs best.
Here's a random YouTube example that seems friendly enough: https://youtu.be/ELz_EG-s0jU?feature=shared

Learn the basics of moving objects in Unity as well as a few different approaches to fit your game needs.
First, you'll learn how to directly change the transform position of your object. Then I'll show you how to move your character using Unity's physics engine so you can correctly collide with other objects.

=========

PlayerController.cs: h...

▶ Play video
regal totem
#

Maybe I wasn't clear, no issue with player movement. Talkin about audio for footsteps, without using animation events.

rich gazelle
regal totem
#

no need to be rude. I get a lot of people come here for the answer instead of looking up. I would not be one of those

queen adder
regal totem
#

you mean like a player IsMoving(Play Sound)?

queen adder
ivory bobcat
left star
regal totem
#

❤️ my apologies for taking it that way then

left star
ivory bobcat
eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

left star
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ThirdPersonMovement : MonoBehaviour
{
    public CharacterController controller;
    public Transform cam;

    public float speed = 6f;

    public float turnSmoothTime = 0.1f;
    float turnSmoothVelocity;

    // Update is called once per frame
    void Update()
    {
        float horizontal = Input.GetAxisRaw("Horizontal");
        float vertical = Input.GetAxisRaw("Vertical");
        Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
    
        if(direction.magnitude >= 0.1f) {
            float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
            float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
            transform.rotation = Quaternion.Euler(0f, targetAngle, 0f);

            Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
            controller.Move(moveDir.normalized * speed * Time.deltaTime);
        }
    }
}

queen adder
wintry quarry
#

They are fighting each other

left star
queen adder
left star
#

i remove rigidbody , but now my player is flying

ivory bobcat
#

Apply gravity through code.

left star
#

ok

wintry quarry
#

It's just doing what your code is telling it to do

digital leaf
#

How to fix license error

left star
#

done!

old schooner
#

been stuck on it for like 3 days

rich gazelle
old schooner
oblique torrent
#

am i allowed to send a long error code here

rich gazelle
oblique torrent
#

alright

#

i googled it apparently its just a bug

#

but i wanna make sure its nothing serious

rich gazelle
woeful hedge
#

how to Deep copy this:

noteCreateTime = midiPlayer.GetComponent<MidiPlayer>().noteStartMS;
woeful hedge
#

List<double>

ivory bobcat
#
var copy = new List<double>(noteCreateTime);```
woeful hedge
#

ohhhh

#

Thanks

main karma
#
public class MoveSystem : MonoBehaviour
{
    public event EventHandler OnTimer;
    [SerializeField] private GameManager manager;

    int nr1 = 0;
    int nr2 = 0;

    private void Awake()
    {
        OnTimer?.Invoke(nr1, EventArgs.Empty);
    }
    private void Update()
    {
        if(manager.state == GameManager.State.Playing)
        {
            nr2 = nr1;
            nr1 = Singleton.Instance.time.ConvertTo<int>();
            if(nr2 != nr1)
            {
                OnTimer?.Invoke(this, EventArgs.Empty);
            }
          
        }
    }

}

How do I send a parameter with the event? I want to send nr1 with the OnTimer event to everyone subscribed but I don't know where to place it

languid spire
main karma
#

trust me I've tried and failed so many times I had to ask

left star
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AnimationStateController : MonoBehaviour
{
    Animator animator;

    // Start is called before the first frame update
    void Start()
    {
        animator = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKey("w")) {
            animator.SetBool("isWalking", true);
        }

        if(!Input.GetKey("w")) {
            animator.SetBool("isWalking", false);
        }
    }
}

#

what is wrong?

languid spire
#

same GetKey

left star
languid spire
#

also you really nead to learn how to ask questions

ivory bobcat
languid spire
#

you only have a transition from Idle to Walking but not back again

left star
left star
rich gazelle
left star
#

i remove the has exit time, and i add the conditions isWalking = true

rich gazelle
languid spire
#

sounds like youve wired up the wrong animations

ivory bobcat
languid spire
#

no need for the second if

#

sorry, Down and Up

ivory bobcat
#

Ask the dudes in #🏃┃animation about your animation. Show them your setup and stuff.

rich gazelle
ivory bobcat
#

Or one of those other low poly ones etc

rich gazelle
#

yeah then I don't think it's a rig problem, it might be due to his animation controller setup is the more likely cause

pine sedge
#

how do i follow a gameobject in scene view during play-mode?

rich gazelle
#

or double tap F, one of those

pine sedge
solar tide
#

Hey, I was watching a tutorial and the URP creation options are totally off from one another.
This is what the tutorial options show

#

My options

vernal thorn
#

i made that my game is in 1920x1080 and still my game is wide (my monitor is 2560x1080)

solar tide
#

Which one should I pick to stay consistent with the tutorial

vernal thorn
#

how can i fix that

rich gazelle
vernal thorn
fading slate
#

I am following a tutorial and i go to a point where i need to add a prefab as a rigidbody but it doesnt work

rich adder
summer stump
rich gazelle
#

under project settings

vernal thorn
#

i found it, thanks 🙂

main karma
#

does anyone have a syntax on how I can pass an int in an event

#

because I still don't get it

polar acorn
main karma
#

wait I think I got it now

#
  public event EventHandler<int> OnTimer;```
#

so I do this right?

#

now instead of the stupid EventArgs I do myInt

fluid remnant
#

cs MyEvent?.Invoke(69)

polar acorn
main karma
#

thank you, I never knew what the <> are supposed to do in C#, I thought I need to pass it in EventArgs as some kind of dictionary cuz I was confused

dusk minnow
#

hey i need some help, i have this object and i want it to rotate like a turret to a target, but i cant ge it to rotate around the right axis

uncut shoal
#

how do I create a custom sprite and generate a custom physics shape with an outline tolerance of 1 instead of the default 0?

#

with code

fossil harness
main karma
#

I see

#

I wish I knew that sooner

#

made many many workarounds

fossil harness
#

Oooof yeah there's a lotta stuff that can be easy to gloss over

fading slate
#

at script

#

at Rb 2d

fossil harness
#

I went two years in uni without knowing what a foreach loop was 😓

main karma
fossil harness
#

Damn RIP

fading slate
uncut shoal
#

So uh can someone help me? I want to generate a custom physics shape using the Sprite Editor but with code for a sprite generated at runtime

#

with an outline tolerance of 1.

#

no idea how to do it though

fossil harness
summer stump
#

Also, keep in mind that there are many of components and methods specific to 2D

If it won't let you drag it in, (or doesn't work in some other way) check for a 2D version.

trim sun
#

!code

eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

vernal thorn
#

i gave a gameobject the button component and still cant click it

main karma
short hazel
vernal thorn
rich adder
vernal thorn
vernal thorn
rich adder
vernal thorn
rich adder
main karma
rich adder
main karma
rich adder
main karma
topaz rain
#

Hi, i've got a question about performance.
If i want to access to a public variable in a script which has no duplicates in the scene, is it better to have a reference to the object owning the variable, or making the variable public static so i dont need to reference the object?

summer stump
#

But without details, can't really say more. It MIGHT make sense to make it static, but it is often not a good idea for just ease of access

topaz rain
#

Well, since i have no problem in referencing the script through the inspector (both objects are always in the scene), and i was only using it to keep the inspector cleaner, i guess referencing the script is the way to go. Ty so much i can imagine making the vars public static has some other use that i'm not aware of and i was just being lazy

summer stump
last grove
#

whats the best way to rotate an object on one axis without touching any of the other axis? orientation.rotation = Quaternion.AngleAxis(yRotation, orientation.up);This is what I have so far but it is not working.

last grove
rare basin
#

why not?

#

you can even smooth this up without using any your own Lerp funfctions etc

valid aspen
#

Object Reference Issue

last grove
# rare basin why not?

Im looking for a function that doesn't rotate every frame, I just want it to update when the mouse moves

#

That's why RotateAround isn't working for me

rare basin
#

you didint answer my "Why not" question

#

im not talking about RotateAround

sharp abyss
#

Frozen is never true but dont know why

last grove
rare basin
#

get it from asset store, watch tutorials on dotween

last grove
#

I figured it out

rare basin
#

that will be your most needed asset ever

#

in every project

sharp abyss
#

can someone take a look at my thread

last grove
#

I need a tool that can rotate just one axis without ever touching the others

short hazel
#

transform.Rotate will do that just fine, you can even tell it to rotate along the world-space axes instead of the local ones by default

last grove
short hazel
#

Then you can use Quaternion.Euler(x, y, z) and pass the angles in degrees

#

It gives back a Quaternion you can assign to any transform.rotation

last grove
#

but that involves setting all the axis values even though I only want to change the y

#

I wish there was a way to add quaternions like you can with vector3

summer stump
short hazel
#

Multiply them to accumulate quaternions

#

But that would be just equal to using transform.Rotate

#

What you can do is store individual x, y, z as floats in the script, change any of these variables and construct the quaternion on the fly

last grove
restive berry
#

Hello everyone,
Im completely new to this and I hope this is the correct channel

    void Update()
    {
        while (Input.GetKeyDown(KeyCode.Space))
        {
            rb.velocity = Vector2.up * upwardsForce;
        }
    }

I want my player to move upwards while the spacebar is pressed. However instead of working, my unity freezes the moment I test my game and press spacebar once. Where did my thinking went wrong? Any tips?

slender nymph
#

don't use a while loop. Update is called every frame so just use an if statement

short hazel
#

It's because of the while loop. Unity does not render the next frame until all the scripts have finished running. And since Input.GetKeyDown can only change between two Update runs, then your condition is always true, your loop never ends, and unity freezes because it does not render the next frame

#

You will need to force stop Unity through task manager, unsaved progress will be lost

restive berry
#

Oh, makes sense, thanks.

How would I implement my goal if not with a while loop? If I use an if statement I have to press my spacebar everytime I want my player to go up, however thats not wuite what im aim to achieve.

short hazel
#

Just an if statement yes

#

If it's a "go up while you press the key down" thing, then use Input.GetKey() instead

tawdry rock
#

Input.GetKey(KeyCode.Space)

restive berry
#

ahh got it the moment you wrote it xD

#

but thank you!

opaque mortar
#

i made a simple script for crouching but now when you crouch the only whey to stop is to sprint there is my code

tawdry rock
#

GetKey is countinous
GetKeyDown is for single frame

short hazel
#

Please share !code according to the instructions below

eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

short hazel
#

Screenshots of code are not editable, copyable, and do not include line numbers

#

And please format the code before posting, so the indentation is correct

left star
#

hi guys someone know some tutorial for make a teleport inside an house?

rich adder
left star
tawdry rock
#

Im very new at unity (1 month old~) so don't go rough on me for my newbie question but i need some light in my head maybe someone can help.
I have a very basic scene setup where the cube spawn exactly a position where a empty gameobject called "Spawner" is located. This spawner is the child gameobject of the Parent.
Parent's XYZ position is: 0,1,2
the Spawner XYZ position is: 3,0,0
I also made a simple blue cube saved it as a prefab (its XYZ position is 0,0,0 but since i spawning it and set its coords it doesnt matter i guess).
Then i made the spawner.cs script and put it on the Parent gameobject. Pressed the pause button then the Start because the code is inside the start method. I also debugging 2 times which gives the box XYZ coords back to console.
First it says the XYZ is: 3,0,0 ( so it spawns exactly where the spawner is.)
Then it says the XYZ is: 3,1,2
In the code i update the cube position two times. Once with transform.localPosition and then with transform.position

What i don't understand when i update it second times shouldn't the position be 0,1,2?
As far as i know, transform.position is for the 'world position' and takes values from the gameobject where the script sits on. With this example it should be the Parent but it ignores the X axis and only updates on YZ.

public GameObject boxPrefab;
 public GameObject spawn;

 private void Start()
 {
     GameObject boxPrefabGameObject = Instantiate(boxPrefab); 

     boxPrefabGameObject.transform.localPosition = spawn.transform.localPosition;
     Debug.Log("Box position is: " + boxPrefabGameObject.transform.localPosition);

     boxPrefabGameObject.transform.position = spawn.transform.position;
     Debug.Log("Box position is: " + boxPrefabGameObject.transform.position);
 }
rare basin
slender nymph
dawn sparrow
#

Before writing to this file, I want to clear it of all previous content

#

How do I do that?

#

I tried different things like opening the file with trucate mode and closing it but I did something wrong, cuz it didnt work at all

slender nymph
#

why are you using File.AppendText if you want to overwrite the content that is already there?

dawn sparrow
#

Not versed in all the different kinds of writing to files

slender nymph
#

you don't even need to use a StreamWriter for this. just use File.WriteAllText

dawn sparrow
#

First time, actually

#

I just used that cuz that's what came up when I searched how to write to a file

vital pumice
#

So I know that if I have a script that updates a text file it doesn’t tend to update until I tab out then back into unity where it does the loading thing
How do I trigger that behavior from script so I don’t have to tab out and in to update stuff?

slender nymph
vital pumice
#

Ah yeah I think so thanks!!

main karma
#

If I have 2 identical components in an object and I use the GetComponent<>() function to get one of them, how do I choose which one I want or switch between them

#

they are the same components but hold different data which I have to access from a 3rd function

slender nymph
#

you don't get to choose or switch. GetComponent will return the first component it finds of that type. you could instead use GetComponents and that would give you an array of all of the components of that type which you could do whatever you need to with. a better option would be to serialize references to those specific components and/or have them on separate child objects

main karma
main karma
main karma
#

so the GetComponents got me to a different question, how do I go through them in a loop

summer stump
main karma
#

like

for (int i=0; i<endvalue;i++) {
do stuff} ```
doesn't work because idk what's the endvalue
rich adder
#

the length of the array

main karma
#

yeah idk how to find that out

summer stump
#

array.length

main karma
#

ah thank you

summer stump
#

Right? Or is it count

#

Check that link

rich adder
#

count is list

#

because size is undetermined / not fixed
so its not a length

summer stump
#

Ok, thought so. Thanks

main karma
#

wish I would've done c# in school instead of c++

rich adder
#

its pretty easy if you already learned C++

main karma
#

we only did fundamentals, from functions to algorithms and classes, structs and all those basic things

#

didn't get into any software specific application

rich adder
#

thats all you need pretty much

eternal needle
#

schools rarely teach it, and really all you need to learn from schools is the concepts. swapping from c++ to c# shouldnt be that tough syntax wise

main karma
#

just cmd apps

eternal needle
#

if you learned like functional programming, then swapping to something else would be pretty hellish

#

or tried to swap into it

main karma
oblique gazelle
#

hello

rich adder
oblique gazelle
#

i need some help

#

?

main karma
#

still got a lot to learn tho

main karma
rich adder
#

do you have visual studio ? create a nice Console apps
You can use unity too ofc and run it in 1 script to keep it simple enough

main karma
#

yeah I have visual studio

rich adder
main karma
#

very useful

solid timber
#

Hey guys, I was wondering, is there a way to Debug within only one C# script?

When I press "Attach to Unity" and try to debug my code, after it has gone through code in Update(), it jumps to cinemachine script and user input script, but I would like it to go on to FixedUpdate() within the same script instead. Is that possible?

solid timber
rich adder
#

instead of step into

#

I could be remembering wrong though lol maybe someone will correct

solid timber