#💻┃code-beginner

1 messages · Page 605 of 1

inland saddle
#

I dont know if this makes much sense but I have been tearing the internet apart trying to just figure this out

#

The whole idea is that a trigger can display a ui element (already got this figured out) and then from there you can hit a key to progress it? in a way between multiple diffrent ui elements you have sorted (like flipping through a book or comic in a way? or like going through dialouge) and then just hiding the element when done, if that makes sense??

#

I dont know what keywords id have to search up or any better way to look for this, and it seems so simple but I have been stressing over figuring this out for weeks at this point

teal viper
inland saddle
#

I have a UI element that shows up on trigger enter for little interaction spots

#

one second let me figure out the format for sending code

teal viper
#

!code

eternal falconBOT
inland saddle
#

oh yay!

#

thank you

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

public class pleasefuckingwork : MonoBehaviour
{
    public GameObject tool;

    void OnTriggerEnter(Collider hit)
    {
        tool.SetActive(true);
    }

    void OnTriggerExit(Collider hit)
    {
        tool.SetActive(false);
    }
}
#

its nothing special but it does the job

#

I will admit I am much more of a visuals guy so coding and everything is so completely new to me

#

My idea was that i could make an alternative version of this code that calls the hiding of the ui to the end of my ui sequence ?

#

I have a kind of similar system in my game for reading these mini books but thats set to button presses

teal viper
#

From the image you shared earlier, you want to scroll between the different ui objects on key press and then disable it, no?

inland saddle
#

mhm!

teal viper
#

The simplest way you can do it is have all the UI objects under a single parent that has a UI script. When you enter the trigger, activate the object with the script. Then in the script update query input and if the desired key was pressed, activate the next child object(or an object in a list). When there is no next UI object, just disable the root object.

inland saddle
#

ooo

#

ok, let me see if i can do this

#

thank you so much for the advice and direction!

hot harbor
#

I was wondering if this implementation of AStar looks like it's behaving correctly? There's only the grid existing on screen, and nothing beneath.

My current understanding is that the heuristic does not change based on if there's obstacles or not since it's "blind" in a sense

#

pink is obstacle and cyan is the steps of the algorithm; yellow is the final path taken

west radish
#

yes

tulip nimbus
#

How do i check if certain colliders touch each other? Whenever im using OnTriggerEnter/Exit/Stay it works for all colliders on the gameobject or all colliders in parent/children

I have a sword with a collider, and an enemy with 3 colliders:

ColliderR- Collider Trigger for player range detection
ColliderP- Collider for Physics
ColliderH- Collider Trigger for a Hitbox (This is what the Sword should be able to hit)

However, all of them are working, which is not what i want. This is the script on the Sword im currently using with an Interface:

private void OnTriggerEnter2D(Collider2D other)
{
  if (SwordCollider.IsTouching(other) && other.CompareTag("Enemy")) 
        { 
        IDamageable damageable = other.GetComponent<IDamageable>();

        if (damageable != null) 
        {
            damageable.TakeDamage(1);
        }
    }
} 
    ```

The sword script also basically has an Attack() function which dissables/enables the script whenever the player attacks.

Ive tried to put the colliders as Variable fields in the Inspector, but using something like: ``` if(other == ColliderH) ``` did not seem to work.

So how can i detect if SwordCollider is touching any, but only one, of the colliders?

What am i doing wrong?
timber tide
#

Could be a composite collider problem? Usually I try to keep stuff separated when doing multiple trigger colliders, making sure I have a rigidbody for each collider *collider for each game object, sorry!

#

Rather, the sword itself wouldn't have an RB, only colliders. Make a gameobject for each hitbox of the sword and stick a collider on that. The enemy will do the OnColliderEnter methods and check what hitboxes of the sword had made contact

#

I think that's what I do? Just woke up ;p

tulip nimbus
#

And do you think there is a way to access them trough code or is it done just trough the inspector

timber tide
#

You only need 1 rb, and that would be on the enemy. This is assuming your weapon is moved not with physics

tulip nimbus
#

oh okay

timber tide
#

because the enemy is the one who reacts to the sword hitboxes. The sword shouldnt care what enemy it hits

#

but for the most part, to use these trigger collider methods, at least one rigidbody must be present. But, you can set the rigidbody as kinematic if you don't need the physics.

#

techically all this collider stuff is physics related, but you're just using it for intersection detection

#

and the object that does have the rb on them will be the one who receives the callback for when there is an intersection.

timber tide
#

one of many ways to do it

gray pawn
#

should i be getting errors?

slender nymph
#

absolutely you should. you haven't declared most of the variables you are using and you've got a bunch of things misspelled

timber tide
#

where's the tutorial you're following

gray pawn
# timber tide where's the tutorial you're following

FIRST PERSON MOVEMENT in 10 MINUTES - Unity Tutorial

In this video I'm going to show you how to code full first person rigidbody movement. You can use this character controller as final movement for your game or build things like dashing, wallrunning or sliding on top of it.

If this tutorial has helped you in any way, I would really appreciate...

▶ Play video
#

its this one

timber tide
#

go over the video again

#

there's quite a bunch you've missed there

gray pawn
#

im guessing its this bit

craggy hinge
#

How do I get the X,Y coordinates of a mouse click? I'm getting weird inconsistencies with ScreenToWorldPoint. I am making a 2D game and I am trying to determine the int X,Y coordinates of where the player clicks on something. All of my interactable objects (dungeons, monsters, player, etc.) are stored in Vector3 lists:

public static List<Vector3> dungeonPositions = new List<Vector3>();

Using dungeons for an example, I currently get the clickedPosition and then round the X,Y into a new Vector3 which I use to compare to all dungeon positions. I do this because when I'm generating the dungeons, they're using int X,Y coordinates and the ScreenToWorldPoint gives a float.

if (Input.GetMouseButtonDown(0))
{
    bool withinInteractionRange = false;
    Vector3 clickedPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    int pOne = Mathf.RoundToInt(clickedPosition.x);
    int pTwo = Mathf.RoundToInt(clickedPosition.y);
    position = new Vector3(pOne, pTwo);
    BoardManager.CheckInteractionRange();
    foreach (Vector3 dungeon in Dungeons.dungeonPositions)
    {
      if (dungeon == position)
      {
      InfoGUI.EnableInfoGUI(position, "dungeon", withinInteractionRange);
      }
    }
}

This seems to work sometimes but about 3/4ths of the time it doesn't do anything. I am guessing the issue is where I'm converting the clickedPosition into individual integers but I'm not sure. Does anyone have any suggestions for how best to accomplish this? Thanks!

slender nymph
#

you probably want to floor X and Y from the mouse position to get the actual coordinate space that was clicked rather than just the nearest coordinate (which could be the next grid space over), but also unless each of the objects in that list only has a size of 1,1 (in grid space, not scale) then what you are doing won't work.
consider using something like the event system IPointer interfaces for detecting clicks on the individual objects instead of checking against every single object on the map for each and every click

craggy hinge
# slender nymph you probably want to floor X and Y from the mouse position to get the actual coo...

Thanks for the reply. I'm fairly certain everything on each grid is set to 1,1 - I'll attach a screenshot of the Structures grid I have. For IPointer interfaces, I'm not sure that would work because I'm not generating any new game objects at run time. Everything on the game board is currently stored in lists that I iterate through and work with across all of my scripts, updating the individual tiles on each grid via coordinates when I need to.

slender nymph
#

i don't know what your screenshot has to do with what you've said. but if you are using tilemaps and all of the objects are actually part of the tilemaps then you can use both the grid and tilemap to get the correct positions and the object at that position instead of using pointless lists

craggy hinge
#

Ah, I misunderstood what you meant about grid space not scale. I guess I'm not sure where to check what the grid size is? I have left them all on whatever their default is I guess.

dreamy dune
#

what is the best way to find another gameobject in the scene trough code?

slender nymph
#

i was specifically referring to the actual objects. if they are not each 1 unit wide and 1 unit tall then what you were doing would break down immediately even if it were almost correct

modest dust
craggy hinge
dreamy dune
#

i want to set the parent of my camera to follow a gameobject in my player

slender nymph
dreamy dune
obsidian plaza
#

if the parent changes then do that

dreamy dune
#

allright

slender nymph
obsidian plaza
#

but if its always the same then u can save some power by getting a reference

dreamy dune
#

its for using in multiplayer

obsidian plaza
#

that doesnt rly explain

craggy hinge
dreamy dune
#

so i have my player object and a camera object and when i join server i need to have a ref to the camera object

modest dust
dreamy dune
modest dust
dreamy dune
#

not really

obsidian plaza
#

oh wait

#

u could just add it to the prefab

#

wait not that wont work

modest dust
#

Then you don't need to find anything at all, just add it to the prefab

obsidian plaza
#

still cant pass reference

modest dust
#

Unparent it later if you need to

obsidian plaza
#

can u

hexed terrace
#

Assuming you only have 1 camera in the scene .. Camera.main

dreamy dune
#

allright i thought that wasnt a good solution to add camera to player

dreamy dune
obsidian plaza
#

what

hexed terrace
#

Camera.main.transform.parent

dreamy dune
#

thank you

vocal urchin
#

I'm literally just trying to make a pinball table but never done 3d before. Should be easy for a 3d expert 🙂
Any idea why my flipper keeps snapping back to 45 degrees rotation on the X axis?

    public Rigidbody rigidBody;
    public Quaternion defaultRotation;
    public Vector3 targetRot;


    
    void Start()
    {
        if (flipperType == FlipperType.LEFT)
        {
            FlipperController.instance.OnLeftFlipperActivated += ActivateFlipper;
            FlipperController.instance.OnLeftFlipperDeactivated += DeactivateFlipper;
        }
        else
        {

            FlipperController.instance.OnRightFlipperActivated += ActivateFlipper;
            FlipperController.instance.OnRightFlipperDeactivated += DeactivateFlipper;
        }
        //defaultRotation = rigidBody.rotation;
    }

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

    private void FixedUpdate()
    {

        rigidBody.MoveRotation(Quaternion.Euler(0, targetRot.y, 0));
    }

    public void ActivateFlipper(float angle, float flipTime)
    {
        float a = Mathf.LerpAngle(rigidBody.rotation.y, angle, flipTime * Time.deltaTime);
        targetRot = new Vector3(rigidBody.rotation.x, a, rigidBody.rotation.z);
    }

    public void DeactivateFlipper(float angle, float flipTime)
    {
        float a = Mathf.LerpAngle(rigidBody.rotation.y, defaultRotation.y, flipTime * Time.deltaTime);
        targetRot = new Vector3(rigidBody.rotation.x, 0, rigidBody.rotation.z);
    }

    public enum FlipperType { LEFT, RIGHT };    
}```
#

This is how the flipper is set up

verbal dome
#

Quaternion.x/y/z dont make sense here

timber tide
#

oh yeah good catch, similarly you're using lerp angle on two quaternions... does that even work

#

I mean, you got the idea of rotating on the y, and that's all you need to do really if it's only rotating one axis.

vocal urchin
#

ooooh

#

so I want rigidbody.rotation.eulerangles?

timber tide
#

Ye. Personally I would just pivot the flipper in a position and have two y values it could possibly be at so I only need to lerp a float.

vocal urchin
#

I think I really need to learn what a quaternion actually is

grand snow
# vocal urchin I think I really need to learn what a quaternion actually is

Go experience the explorable videos: https://eater.net/quaternions
Ben Eater's channel: https://www.youtube.com/user/eaterbc
Help fund future projects: https://www.patreon.com/3blue1brown
An equally valuable form of support is to simply share some of the videos.
Special thanks to these supporters: http://3b1b.co/quaternion-explorable-thanks

Pre...

▶ Play video
inland saddle
#
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;

public class KeypressManager: MonoBehaviour
{
    public GameObject dialouge01;
    public GameObject dialouge02;
    public GameObject parent;

    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown("enter"))
        {
            dialouge01.SetActive(true);
        }

       if (dialouge01.activeSelf) {
                if (Input.GetKeyDown("enter"))
            {
                dialouge02.SetActive(true);
                dialouge01.SetActive(false);
            }
        }
        if (dialouge02.activeSelf)
        {
            if (Input.GetKeyDown("enter"))
            {
                dialouge02.SetActive(false);
                parent.SetActive(false);

            }
        }
    }
}

#

doing this feels so deceptively simple and just I really am trying

shy kite
#

i suppose you slowed it a bit for showcase

inland cobalt
#

If i want a class to inherit from multiple things, such as this:

public partial class Enemy : Poolable<Enemy>, Damageable<Enemy>
{
  //...
}

How can i best go about doing it? As it cannot have multiple base classes

slender nymph
#

based purely on name alone Poolable<T> and Damageable<T> seem like they should probably be interfaces, but you've not really provided enough context to know for sure

cosmic dagger
inland cobalt
#

I see, i made them abstract as i wanted to provide default implementations for them, so i thought that was best. As far as i know i cant define variables in an interface so im not sure how to go about it otherwise

slender nymph
#

you can have properties in interfaces. what is the actual purpose of these and why do you need both

inland cobalt
#
public abstract class Damageable<T> where T : MonoBehaviour
{
    public float Health { get; private set; }

    public virtual bool Damage(float damage)
    {
        Health -= damage;
        if(Health < 0) 
        {
            Die();
            return true;
        }

        return false;
    }

    protected abstract void Die();
}```

example
timber tide
#

I'd make IPoolable an interface for the Enemy to inherit implement

cosmic dagger
cosmic dagger
ivory bobcat
slender nymph
timber tide
#

here's an idea too

public abstract class ObjectPool<T> where T : MonoBehaviour {} //Can also make this a monobehaviour class / singleton to child the enemy instances
public class EnemyPool<Enemy> {}```
cosmic dagger
inland cobalt
#

I see, is something like this fine though?

[DefaultExecutionOrder(-1)] // Ensures singletons can always be accessed by prioritising their execution
public abstract class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T instance;
    public static T Instance
    {
        get
        {
            if (instance == null)
            {
                T[] instances = FindObjectsByType<T>(FindObjectsSortMode.None);
                if (instances.Length > 1) Debug.LogWarning($"Multiple instances of {instance.name} exist");

                if (instances.Length != 0) instance = instances[0];
                else Debug.LogWarning("Singleton is attempting to be accessed, when none exist");
            }

            return instance;
        }
    }
}```

This was the first time i used this kind of format, so i just replicated, i feel like it makes sense here
inland saddle
#

im sorry

inland cobalt
#

I see what you mean how it makes sense for damaging and stuff to be in seperate monobehaviours though

ivory bobcat
#

Or GameObject or whatever you're needing more than one of.

#
public List<GameObject> dialogues;//to be populated from the inspector etc```
cosmic dagger
ivory bobcat
#

I'm assuming you know about lists and have imported the directives (using collection etc)

timber tide
inland cobalt
inland cobalt
timber tide
#
public abstract class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
    public static T Instance { get; private set; }
    
    protected virtual void Awake()
    {
        if (Instance == null)
        {
            Instance = this as T;
        }
        else if (Instance != this)
        {
            Destroy(this); //Or destroy gameobject depending how you do your managers
        }
    }
}

public abstract class PersistentSingleton<T> : Singleton<T> where T : MonoBehaviour
{
    protected override void Awake()
    {
        base.Awake();
        DontDestroyOnLoad(gameObject);
    }
}```
```cs
public class GameManager: PersistentSingleton<GameManager>```
There, toss that into every project
inland cobalt
timber tide
#
public interface IDamageable
{
  public int Health { get; }
  public void DoDamage(int damageAmount);
  public void DoHeal(int healAmount);
}```
ivory bobcat
# inland saddle not atall

Place this at the top using System.Collections.Generic; to allow yourself usage of Lists.
Create the public List field like my prior example above.
Populate the list with your dialogues. For example, if you had three dialogues, they would be at index 0, 1 and 2 of the list.
The code would run in Update and evaluate if said button was pressed (the statement where I've neglected to complete since you've already done so yourself in your original code posted).
Next you would disabled the current dialogue (assuming the current one is enabled when this script had become enabled). You'd increment the counter (current) by one and evaluate if it's less than the maximum amount of dialogues. If greater than or equal to the maximum count, you'd disable this script to prevent further execution at later times and stop executing the remainder of this Update function with a return call.
If the current index hasn't exceeded the series of dialogues to be presented you'd enable the next one etc.

inland cobalt
inland saddle
#

Thank you so much, I will try my best to follow along

timber tide
cosmic dagger
inland cobalt
ivory breach
#

I tried to make my turret aim at the player with the following method, but when the player gets too close to it, the turret doesn't aim like the game is 2D. Is there a way to fix this issue?

    private void LookAt()
    {
        Vector3 targetDir = GameObject.FindWithTag("Player").transform.position - gun.transform.position;
        float step = rotationSpeed * Time.deltaTime;
        Vector3 newDir = Vector3.RotateTowards(gun.transform.forward, targetDir, step, 0.0f);
        gun.transform.rotation = Quaternion.LookRotation(newDir);

        //gun.transform.rotation = Quaternion.Euler(gun.transform.rotation.eulerAngles.x, 90, 0);
    }
timber tide
hexed terrace
#

Also, stop using FindWithTag() constantly. Do it once and cache it.. there is no reason to do it every frame

ivory breach
hexed terrace
#

newDir.y = 0;

ivory breach
hexed terrace
#

ok, great - I dont need to be told that, just go do it ;p

ivory breach
#

Where did I go so wrong...

hexed terrace
ivory breach
#

All I did was add your suggested piece of code here

#

If I'm missing something, please let me know

hexed terrace
#

Remove that line I said to add.. and wait for someone else to help. I dont have the time to carry on.

Seems to me though you only want to be rotating on Z, but you're rotating on all three axis

wintry quarry
#

Quaternion.LookRotation(newDir, Vector3.back);

#

the problem right now is you're not passsing in a second parameter, so the game assumes you want the global "up" direction to be the "up" direction for your rotation

ivory breach
#

Nope, it still rotates on all three axis somehow

wintry quarry
#

wdym by "rotates on all three axis"

#

show a video

ivory breach
#

I've made sure all of the rotations including the children are set to 0

ivory breach
wintry quarry
#

the only issue I see is the twisting

#

oh I didn't watch long enough

#

your problem then is also that the objects are not at the same z position

#

so you will also want dir.z = 0;

swift crag
#

that means that the turret and player aren't on the same plane

#

i'm mildly unclear which plane the camera is aligned with; assuming it's the XY plane, then yeah, zero out the Z coordinates

wintry quarry
#
newDir.z = 0;
gun.transform.rotation = Quaternion.LookRotation(newDir, Vector3.back);```
swift crag
#

the commented-out code has the gun rotating on the world X axis

wintry quarry
#

yeah this is assuming we're looking at the xy plane here

swift crag
#

which is inconsistent with being aligned with the XY plane

#

if the camera is on the YZ plane, then zero out the X coordinate. Same idea.

#

you can figure out which plane the camera is on by looking at the orientation gizmo with your view aligned with the camera

#

here, I'm on the XY plane

#

...and looking in the +Z direction

wintry quarry
#

actually it's probably targetDir we want to be setting z = 0 on tbh

swift crag
#

Yeah, you can zero out both positions or the resulting direction

#

Same deal

#

The latter is easier

swift crag
#

note that this means that the cannon is no longer aiming at the player 😉

#

Maybe you actually want to fix the player not being on the same Z coordinate as the cannon!

ivory breach
#

@swift crag Btw, it's the xy plane in my case

swift crag
#

yeah, that's the typical setup for a 2D game

#

i was just unsure because of that commented-out line at the end

ivory breach
#

Now to figure out how to clamp their rotations to prevent the turrets from looking down

swift crag
#

Quite a few ways to do that. The most obvious, to me, is to use Quaternion.RotateTowards

#

That lets you move from one rotation to another by at most a certain amount

ivory breach
swift crag
#

Yeah

#

so Quaterion.RotateTowards(Quaternion.identity, targetRotation, 90) produces a rotation that is at most 90 degrees away from the identity rotation

#

"identity" meaning the rotation that does nothing

#
transform.localPosition += Vector3.zero;
transform.localRotation *= Quaternion.identity;
transform.localScale *= Vector3.one;
#

all three of these do nothing

fierce plume
#

How do I Reference or just use a variable from another script?

burnt vapor
eternal falconBOT
thorn holly
hexed terrace
#

dont declare variables as public, its poor encapsulation

thorn holly
#

In that case, use a getter/setter method

hexed terrace
#

Yes, use them. Getter/ Setter is a property though - not a method

vital barn
#

Inside is method

hexed terrace
#

it might decompile to a method, I dunno, but in your C# class.. it's not a method, hence why theyre called properties

thorn holly
#

Well I mean it depends on how you write it

grand snow
#

Properties actually make a get and set function but it's hidden from you

#

If you use reflection you can find these methods and the backing field

vital barn
#

Or just use dnspy

ivory breach
#

Looking back at my code, I honestly don't know how to change this line of code to clamp the x-axis rotation, because the maxDegreesDelta is already taken by "step"

#
Vector3 newDir = Vector3.RotateTowards(gun.transform.forward, targetDir, step, 0.0f);
vital barn
#

eulerAngles

thorn holly
#

It’ll give you more control, including clamping a specific axis

ivory breach
#

If u can suggest a better solution, I'm all ears

swift crag
#

the Z axis, in particular

ivory breach
#

Yes

swift crag
#
[SerializeField] Quaternion centerRotation;
[SerializeField] float angleLimit;

Rotate from centerRotation towards the desired rotation by at most angleLimit

#

where centerRotation is the rotation that makes the cannon point straight up

ivory breach
#

Upon closer inspection, I found something weird with the object's rotation

swift crag
#

You'd just store a neutral direction that you rotate away from

ivory breach
#

The object is apparently rotating in the x-axis instead of z-axis, and depending on where it's pointing, the y and z rotation snaps to 90 and -90 degrees when it's looking right and vice versa when it's looking left

swift crag
#

if you rotate an object around the world Z axis, its local X rotation might change (depending on how its parent is rotated)

#

also note that looking at Euler angles can be misleading

#

there are many ways to represent the same orientation

#

If the cannon is visibly doing the right thing, that's all that matters

ivory breach
swift crag
#

because the inspector is showing the rotation relative to its parent

wintry rampart
#

I am trying to learn this engine i never used anything of this before i am trying to use the tutorial but i dont under stand this can anyone help?

polar marsh
#

Anyone know how i can resolve this error? My script name matches the class name and it inherits from monobehavior, but it just refuses to recognise it

swift crag
ivory breach
#

I've made sure the parent's rotation is zero on all axis

swift crag
polar marsh
swift crag
swift crag
#

Check the console.

polar marsh
#

Even if i delete all the code from the script it still does it

swift crag
polar marsh
swift crag
#

hm, at that point: right click the script asset and click "Reimport". Does anything change?

#

also make sure that you don't have multiple MonoBehaviour classes defined in the same script file

polar marsh
#

It's just one class as well

swift crag
#

can you currently enter play mode?

polar marsh
#

Yep it works fine

swift crag
#

Peculiar.

#

I'd sanity check by making a new MonoBehaviour script asset and seeing if that works

#

If that fails, I'd see if a full reimport fixes it. Assets > Reimport All

polar marsh
#

Doesn't seem to work either

swift crag
#

this'll take a hot minute

polar marsh
#

Alright ill try that

swift crag
#

the Library contains data generated by Unity -- a big chunk of which is the asset database

#

that's what you're clearing with Reimport All

polar marsh
#

Oh i see okay

swift crag
#

(and the X rotation affects the meaning of the Z rotation)

#

When you only have a direction, there are many possible rotations that point you in that direction

#

which could cause unwanted spinning of the barrel

#

I see that you were originally not passing a second argument to LookRotation

#

Are you doing that now?

fathom cape
#

Hello o3o

I have a question I will place in a thread if I can

ivory breach
polar marsh
swift crag
#

That'll keep the barrel's "up" direction -- the green arrow -- facing towards the camera

ivory breach
#

How do I find the turret's local quaternion rotation? Because I want to find its center rotation and I don't trust the rotation values in the inspector anymore

swift crag
#

which direction does the barrel point when its local rotation is zero?

#

You actually want to be working with local rotations here. If the entire cannon body tilts to the side, that should change the field of view of the cannon

ivory breach
swift crag
# swift crag You actually *want* to be working with local rotations here. If the entire canno...

So, your code will look like this:

[SerializeField] Quaternion restRotation;
[SerializeField] float angleLimit;

void Aim() {
  Quaternion goalRotation = ... // do the existing calculation
  
  Quaternion localGoalRotation = Quaternion.Inverse(transform.parent.rotation) * goalRotation;

  Quaternion limitedRotation = Quaternion.RotateTowards(restRotation, localGoalRotation, angleLimit);
  
  transform.localRotation = limitedRotation;
}

Get the barrel rotated to the neutral position, then right click the "Rotation" property and copy the quaternion. You can then paste it into the restRotation field.

#

I wish there was a convenient Transform method to go between local and world rotations

#

goalRotation is a world-space rotation. The second line converts to a local-space rotation.

ivory breach
#

Here are the cannon's rotations in the inspector just to be sure

swift crag
#

Rotate the barrel so that it's in the "center" position

#

then copy its local rotation

#

that's your reference point

#

the cannon will rotate away from that reference point until it reaches the angle limit

humble hound
#

hii can anyone help me

#

i have two jumps, when i jump once it the ball only moves 2 pixels above the ground and it sticks back to the ground coz the gravityon air brought it back down, the ball jumps nicely when on air so the gravityscale on air os not the problem, but there is something happening between that first jump that makes the ball only jump 2 pixels idky

swift crag
#

perhaps you have code that sets your vertical velocity to zero when you're grounded

#

and the ground check is wrongly saying "yes" when you're moving upwards

ivory breach
#

@swift crag I hope I did everything right

void Aim() 
    {
        Vector3 targetDir = GameObject.FindWithTag("Player").transform.position - gun.transform.position;
        float step = rotationSpeed * Time.deltaTime;
        Vector3 newDir = Vector3.RotateTowards(gun.transform.forward, targetDir, step, 0.0f);
        newDir.z = 0;

        Quaternion goalRotation = Quaternion.LookRotation(newDir, Vector3.back);
  
        Quaternion localGoalRotation = Quaternion.Inverse(transform.parent.rotation) * goalRotation;

        Quaternion limitedRotation = Quaternion.RotateTowards(restRotation, localGoalRotation, angleLimit);
  
        transform.localRotation = limitedRotation;
    }
swift crag
#

(make sure your scene view is in "Local" mode, not "Global", here)

#

Otherwise, the barrel will try to spin around its long axis!

ivory breach
#

Should I attach the script to the barrel or its parent?

swift crag
#

As-written, it needs to go on the barrel

#

If you want to be able to put it on another object, you need to add a Transform field

#

(and then rotate that target)

#

basically, any use of your own transform property would be replaced by that field

ivory breach
#

I'll just put in on the barrel to play it safe

#

@swift crag Yeah! It's working!

swift crag
#

nice (:

#

You should be able to rotate the entire cannon body and have it still work right

ivory breach
#

Thx a million!

swift crag
#

can you share that on a paste site? !code

eternal falconBOT
swift crag
#

I need to get to work so I'm out of here for now, but someone else can probably help you with that

wintry quarry
ivory breach
#

@swift crag Btw, the cannon ur talking about is actually a mortar

#

I just suck at designing it to make it look like one

humble hound
#

Im tryna recreate this feature man

wintry quarry
# humble hound

How are you gonna stick to a rotating triangle by setting your velocity to 0?

#

the approach is misguided

#

aand anyway it's responsible for your inability to properly move off the surface

humble hound
#

How would you approach it

wintry quarry
#

Probably without rigidbodies

rich adder
wintry quarry
#

parent the player to the object it contacts

#

but yeah with RB you would use joints and break them when the player jumps again

#

but it won't be exact and clean

#

because physics isn't

rich adder
#

test it out, if dynamic gives you problems, maybe use transforms or kinematic parenting

humble hound
rich adder
humble hound
#

Really wont that cause unintended issues like the object jumping with the ball

rich adder
#

when you jump you break the connection

#

only put it on while its a moving / rotating surface I guess

humble hound
rich adder
#

the former complicates this even further

scarlet hull
#

i have a character 3d model any website or some tool to just auto rig it and apply animations?

humble hound
rich adder
ruby python
#

Af'noon all.......sooooo, I'm trying to get the pixel colour values of an image but ran into a bit of a roadblock.

Here's my full code at the moment

https://hastebin.com/share/liradisati.csharp

The part that I'm struggling with at the moment is where I assign the colour value of the current pixel in my loop

newDepthMapData.valueAtPosition = depthMapValues[  ];

This line specifically, I don't really know what this should be if honest, and the Unity docs have been no help so far.

Idea of the script is that it reads each pixel in turn and creates/adds the data (current position and pixel colour value) to the DepthMapData class and then adds the new class to the list for future processing etc.

Chances are that I've done many things wrong with how I've written in all, but at the moment it's just for prototyping purposes.

Would anyone be able to point me in the right direction please?

polar acorn
ruby python
polar acorn
ruby python
scarlet hull
#

cant seem to add avatar for animator why?

polar acorn
rich adder
scarlet hull
rich adder
#

what is this supposed to show ?

#

there is no avatar here

polar acorn
#

There might be one in the imported mesh

rich adder
#

you have to create the avatar first in the Model import

polar acorn
#

but it's not expanded so I can't see

scarlet hull
#

i want to animate character with the downloaded anims i did create an animator window

steep hollow
scarlet hull
#

correct channel indeed

#

thanks for reminding me

polar acorn
steep hollow
rich adder
steep hollow
#

i dont want him to teleport

#

thats why i said its weird

rich adder
#

so make it not teleport

steep hollow
#

NO WAY I DIDNT THOUGHT ABOUT THAT

#

THANK YOU SO MUCH

#

YOU CHANGED MY LIFE

polar acorn
#

We can't really answer any more detail than that since you haven't posted any code

rich adder
#

I mean without script at least or seeing setup, what do you expect?

steep hollow
#

public class Player : MonoBehaviour
{
private Vector3 motion;
public Rigidbody rb;
public float speed;

void Update()
{ 
    motion = Vector3.zero;

    if (Input.GetKey(KeyCode.W))
    {
    motion += new Vector3(0, 0, 1);
    }
    if (Input.GetKey(KeyCode.S))
    {
      motion += new Vector3(0, 0, -1);
    }
    if (Input.GetKey(KeyCode.A))
    {
        motion += new Vector3(-1, 0, 0);
    }
    if (Input.GetKey(KeyCode.D))
    {
       motion += new Vector3(1, 0, 0);
    }

    motion.Normalize();
    rb.velocity = motion * speed * Time.deltaTime;
}   

}

rich adder
#

you're in code channel and haven't even posted the code with question

eternal falconBOT
wintry quarry
steep hollow
#

lemme try

rich adder
#

also might want to be moving in FixedUpdate

swift crag
#

you use deltaTime to convert "X per second" into "X"

ruby python
#

Hmm. Okay, so everything is now working......sort of. lol. I'm grabbing the correct data from my image and it's all being added to the list correctly, which is cool.

But, I'm getting an index out of range error, and I'm not entirely sure why.

https://hastebin.com/share/ehaqaniwen.csharp

I'm sure there's a better way to do this tbh, as it is going to result in a crapload of entries in the list (80,000 ish before the index things craps it out and if my maths is right, it should be 147,456, which I'll then have to search through on a frame by frame basis, which I imagine will be very slow.

The image is 512*288 pixels.

wintry quarry
#

Anyway pretty sure:

depthMapValues[(x * mapWidth) + y];```
is supposed to be:
```cs
depthMapValues[(x * mapHeight) + y];```
#

and the -1 should probably not be there e.g. in mapWidth-1 unless you are trying to skip the last pixel in each row/column

ruby python
#
Color32 tempColour = depthMapValues[(x * mapWidth) + y];
swift crag
#

generally speaking, you should have:

x * y_size * z_size + y * z_size + z

ruby python
#

Ah okay. Yeah that's the line with the error.

swift crag
#

incrementing x skips ahead by an entire YZ slice

ruby python
#

And yeah, the -1 was just 'checking' with the out of range error.

swift crag
#

in this case, you just have x and y

ruby python
wintry quarry
#

Fen's reasoning is the why!

ruby python
#

Yeah, I'll be honest, the axes stuff in that line confuses the crap out of me. lol.

#

Actually, if I may impose a little further. I've figured out how to cut down on the list entries quite a bit (using an alpha channel and just ignoring anything with an alpha of 0. So that helps.

When it comes to referencing the data in the list and grabbing the colour value, I'm not 100% sure how to go about it.

My thought at the moment is to send Input.mousePosition (with a little calculation to match the size of the depthMap image) to a method that searches the list for the relevant vector2 and returns the colourValue, which will then be used to scale the bullet impact.

But, it seems like that might be really inefficient and slow.

Anyone have any thoughts?

shut warren
ruby python
eternal needle
#

also this code is very questionable, id be pretty wary of this tutorial.

polar acorn
ruby python
#

Ignore what I said btw. Speed reading and read it wrong. lol.

drifting cosmos
normal turret
#

Hey guys, what's up

#

If I want to do a fake collider on one tile in my tileset, how can I do that...?

normal turret
#

Someone recommended I should make a fake collider on another server because I was having issues with wall-jumping

wintry quarry
#

WHat does that mean

#

what kind of issues?
What would a "fake collider" do or mean?

normal turret
#

Like for these steps for example, it thinks these tiles are walls

vital barn
#

It shold be trigger

normal turret
#

I only want to wall-jump if it's 2 tiles or higher

polar acorn
normal turret
wintry quarry
#

and yeah what bug?

normal turret
#

Like sometimes there can be issues with the character moving up a slope, you can add a fake collider and make it seamless

#

I don't know, I'm new to this stuff too, I just heard the concept a couple days ago

polar acorn
# shut warren Yes

CharacterControllers don't like being teleported. You can either disable the controller and re-enable it, or call Physics.SyncTransforms() after the teleport to force it to update

polar acorn
wintry quarry
#

maybe what they mean is to add a simple collider that doesn't match the visual shape of the terrain?

drifting cosmos
normal turret
#

This is what the person shared as a solution

wintry quarry
#

yeah that's just having a collider that doesn't perfectly match the visual

polar acorn
#

Okay, yes, a collider that doesn't match the visuals

barren plume
#

I copied a script I found from youtube video regarding player collisions and movement and I noticed that some of the words werent the right colors and stuff how do I fix this

wintry quarry
#

You can edit the shape of the collider for your sprites in the Sprite Editor under "Custom Physics Shape" @normal turret

normal turret
eternal falconBOT
barren plume
normal turret
#

Or I guess it goes by a different name

wintry quarry
polar acorn
normal turret
wintry quarry
#

Tiles are always individual sprites

normal turret
#

Ok nice thank you, going to try it out

#

It's just sometimes the character wall jumps off of one tile and it's kind of weird

#

So I wanted to see a solution, going to try it out

polar acorn
shut warren
#

Okay

strange tapir
#

is there a way to write logic in pixel coordinates?

public class GroundManager : MonoBehaviour
{
    private Vector2 _spriteSize;
    private Vector2 _gameSize;

    private void Start()
    {
        PixelPerfectCamera pixelCam = Camera.main.GetComponent<PixelPerfectCamera>();
        _gameSize = new Vector2(
            pixelCam.refResolutionX, pixelCam.refResolutionY
        );

        // They are both the same size so it doesn't matter.
        SpriteRenderer sprite = _ground[0].GetComponentInChildren<SpriteRenderer>();
        _spriteSize = sprite.size / sprite.sprite.pixelsPerUnit;
    }

    private void FixedUpdate()
    {
        foreach (GameObject ground in _ground)
        {
            Vector2 position = ground.transform.position;
            position.x -= _movementSpeed;

            Debug.Log($"{ground.name}: {position}");

            if (position.x < 0 - (_spriteSize.x / 2))
                position.x = _gameSize.x + (_spriteSize.x / 2);

            ground.transform.position = position;
        }
    }
}```
im trying to write somethig like this but im writing in pixel size not unit size
barren plume
# eternal falcon

I did this and its still not working so either my pc is stupid or I am

wintry quarry
#

when your game resoluition changes it will be different

#

If you mean something like sprite pixels rathjer than actual on-screen rendered pixels then yeah you would use e.g. the sprite pixels per unit as in that code to convert

#

if you have 32 PPU, for example, then 1 in-game unit = 32 "sprite pixels"

strange tapir
#

i did smth like this

cosmic charm
#

Is it possible to make the cloud respond to the player's steps, so that it sinks when the player steps on it and sinks further if the player lands on it after jumping?

swift crag
#

some things are just very, very annoying (:

#

It sounds like you have a couple of smaller problems here:

  • Detecting that the player is standing on a cloud
  • Detecting that the player just landed on a cloud
  • Warping the shape of the cloud
cosmic charm
#

this should be made through code, right? it's not about animation? like it would be dumb to make a version for each cloud depending on the the player's movement

timber tide
#

you can do it by animation

drifting cosmos
#

yeah might be really easy

timber tide
#

but this is simple enough to just do it all in code

cosmic charm
#

let me explain

swift crag
#

hm, i'm not sure about how I'd distort the individual sprites in a tilemap

#

since that's one big mysterious Tilemap Renderer

timber tide
#

Can't you mix both? Tilesets and just single GOs?

#

Didn't even occur to me that you can use tileset for 2D platformers ;p

cosmic charm
#

like what if he wasn't in the middle of the cloud?

drifting cosmos
#

like you could have 3

#

animations

#

and since the guy is big enough you wont need more

cosmic charm
#

like I was thinking of implementing the same logic of the water

drifting cosmos
#

to like flat

cosmic charm
#

yes

#

can I send links here of a youtube tutorial?

#

or will i get banned?

drifting cosmos
#

idk but i think you can have smaller tiles so like for the water one you can have the middle tile the one all the way down and the ones on the side you can have them in a different state

night raptor
cosmic charm
# drifting cosmos idk but i think you can have smaller tiles so like for the water one you can hav...

Show your Support & Get Exclusive Benefits on Patreon (Including Access to this tutorial Source Files + Code) - https://www.patreon.com/sasquatchbgames
Join our Discord Community! - https://discord.com/invite/aHjTSBz3jH

--
I had......SO much fun working on this project... Despite having to completely scrap my first approach!
We're going to use ...

▶ Play video
humble hound
#

m_Rigidbody.linearVelocity = new Vector2(0f, m_Rigidbody.linearVelocity.y);

wintry quarry
#

same problem

#

agian look at that rotating triangle part

#

that's not going to work with some hardcoded velocity hack

slender nymph
# humble hound m_Rigidbody.linearVelocity = new Vector2(0f, m_Rigidbody.linearVelocity.y);

this is not related to your issue but fun fact: if you are on a version of unity where the velocity property is called linearVelocity then you also have access to the linearVelocityX and linearVelocityY properties to only assign a single axis instead of both
(for anyone else reading this, this only applies to rigidbody2d which they are clearly using, not rigidbody)

humble hound
cosmic charm
humble hound
final trellis
#

probably a dumb question but how do i resolve this error? quick actions and refactoring isnt helping much

slender nymph
#

why are the constructors private?

wintry quarry
final trellis
wintry quarry
#

and the constructor will need to be at least protected to do that

#

AbilityCard(string cardName, Image cardGraphic, char identifier, int damate) : base(cardName, cardGraphic, identifier, damage) {}

final trellis
slender nymph
#

it's like private, but inheriting classes have access too

#

private = only this object has access
protected = this object and inheriting objects have access
public = all objects have access
internal = only objects within this assembly have access

wintry quarry
#

Man I really wish we had access to the file modifier in Unity...

final trellis
#

this is like when science teachers tell you there are only 3 states of matter and then you find out later there are secret more evil ones

#

well i knew abt protected from college but the teacher never explains why things exist and only just what they are

polar acorn
swift crag
#

wait until you find out about file

warped jasper
#

So guys whenever I put my script with the player movement and with animation, when I put the rigid body in, it doesn’t work like it it just straight up doesn’t work like the rigid rigid body just doesn’t work

warped jasper
wintry quarry
#

That doesn't make much sense

#

if you have a player movement script that works without a Rigidbody what's the Rigidbody for

#

Sounds like you're trying to mix multiple different forms of movement

#

that's a no-no

#

and it's not gonna work

warped jasper
polar acorn
wintry quarry
polar acorn
# warped jasper no

If you disable the animator component, does it properly fall and get controlled

warped jasper
#

lemme check

#

yes

polar acorn
#

So then your animation affects the transform of the object

warped jasper
#

oh

polar acorn
#

You shouldn't be animating the object with the rigidbody. Your mesh should be a child object of that

#

That way it can be animated without affecting movement

warped jasper
#

thanks

final trellis
wintry quarry
#

Depending on the circumstances it could actually be less private than private

swift crag
#

we happen to be in a voice call together and i already pointed this out

#

owned

wintry quarry
#

Lol

swift crag
#

see also: publicer staticer, which means the value is stored on the internet

#

a pvp-enabled zone

slender nymph
#

where's the battle royale access modifier where objects have to fight over access to a member and only the last survivor can do so

swift crag
#

that's just the singleton pattern where objects destroy themselves

polar acorn
#
try {
  //access variable
} catch {
  Destroy(this);
}
final trellis
#

and then u got publicerererererer which gives the observable universe access

last radish
#

Im tryinh to make procedural wall generation for the backrooms, and stumpled accross this video(https://www.youtube.com/watch?v=wQj-l0vDQsA that describes how he generates walls. At around 3:13 he slightly explains it but i have no clue how to actually do it. Could someone help?

inland sable
#

hello

#

I have an error to send the raycast

#

It don't sow in editor mode

polar acorn
#

What's the error?

daring crescent
#
        if(Input.GetButtonDown("Jump"))
        {
            jumpPressed = true;
        }

        isGrounded = groundCheck();

        playerVelocity.x = moveDir * moveSpeed;
    }
    void FixedUpdate()
    {
        // Jump Logic
        if(jumpPressed && isGrounded)
        {
            rb2d.AddForce(Vector2.up * jumpHeight, ForceMode2D.Impulse);
            jumpPressed = false;
        }
        
        rb2d.linearVelocityX = playerVelocity.x;
    }

How could i write this easier without the if(Input.GetButtonDown)
I had jumpPressed = Input.GetButtonDown; before then i have huge input loss.
I need to press 10 times spacebar 😄

Someone can give me a hint how to handle Input in Update and AddForce in FixedUpdate?

inland sable
polar acorn
polar acorn
#

That's how you'd do that

daring crescent
#

oh you mean as a one liner

inland sable
polar acorn
thorn holly
inland sable
polar acorn
# inland sable now its go to up

Is the issue still the DrawRay not working? Because I didn't see you ever go check it in the scene view to see if it was visible

cosmic dagger
#

Dude went into outer space . . .

verbal dome
thorn holly
# inland sable now its go to up

It’s either a jump force issue or a jumping multiple times issue, from the looks of it. I’d do a debug log for the jump, see if it’s getting called many times or just once, if it’s many times something’s wrong with your ground detection, otherwise, your jump force is too high

polar acorn
thorn holly
inland sable
thorn holly
#

Are you in scene view and the game is running?

thorn holly
thorn holly
# inland sable

And here you are in the scene view, but the game is not running

inland sable
polar acorn
inland sable
polar acorn
thorn holly
inland sable
thorn holly
inland sable
#
using UnityEngine;

public class MoveStickman : MonoBehaviour
{
    public float Speed;
    public float JumpForce;
    public float DistanceToGround;
    private bool TouchGround;
    private Rigidbody2D rb;
    private Animator animator;
    private float horizontal;
    

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

    // Update is called once per frame
    void Update()
    {
        horizontal = Input.GetAxisRaw("Horizontal");
        animator.SetBool("Walking", horizontal != 0.0f);

        if (horizontal < 0.0f) { 
            transform.localScale = new Vector3(-1.0f, 1.0f, 1.0f);
        } else if (horizontal > 0.0f) { 
            transform.localScale = new Vector3(1.0f, 1.0f, 1.0f) ;
        };

        Debug.DrawRay(transform.position, Vector2.down, Color.red);
        if (Physics2D.Raycast(transform.position, Vector2.down, DistanceToGround)) {
        TouchGround = true;
        } else {
        TouchGround = false;
        }
        if ((Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.Space)) && TouchGround) {
            Jump();
        };
    }


    private void Jump()
    {
        rb.AddForce(Vector2.up * JumpForce, ForceMode2D.Impulse);
    }
    // FixedUpdate is called at a fixed interval and is independent of frame rate
    private void FixedUpdate()
    {
        rb.linearVelocity = new Vector2(horizontal * Speed, rb.linearVelocity.y);
    }
}
#

it is

thorn holly
cold mist
#

i know this is a weird question, but how do i make an object move almost towards the mouse?

#

and not exactly at the mouse position

coral crater
#

is it generally okay to check something that may be null? there's a possibility that prevPlace will be null at the point of checking. I assume that won't throw any errors, or is this problematic?

grand snow
#

yea you can compare null to something just fine

#

but you cant do null.foo() ofc

slender nymph
#

if it could possibly be null then you definitely should null check it before actually using it. however you probably should store the objects returned by those method calls in variables if you will need to use them again (like in the if statement)

modest dust
#

What are you trying to do

#

If you mean that you want to slightly offset the movement direction then get the proper direction vector and rotate it by however much you want

coral crater
#

thanks for da advice :)

honest iron
#

HI,im getting error here

public void SelectSP(GameObject SP)
{
    if (selectedSPCount < 2)
    {
        selectedSPBox[selectedSPCount].SetActive(true);

        //set seleced SP image and text
        selectedSPsImages[selectedSPCount].GetComponent<Image>().image = SP.GetComponent<Image>().image; //error
        selectedSPText[selectedSPCount].text = SP.name;

        SPToSelectImages[selectedSPCount] = SP;
        SP.SetActive(false);

        selectedSPCount++;
    }
}

ArgumentException: GetComponent requires that the requested component 'Image' derives from MonoBehaviour or Component or is an interface.

polar acorn
rich adder
#

Check your namespaces

honest iron
#

no

polar acorn
#

Or are you importing a namespace that does?

grand snow
#

could be System image or something by accident instead of UnityEngine.UI

rich adder
#

hover over the Image class, if its not from UI namespace, then its wrong one

polar acorn
#

The .image shows that it's definitely the wrong class, Unity's Image doesn't have a property by that name

slender nymph
#

yeah seems like they may be using the UIElements.Image

rich adder
#

tru true. its just .sprite

honest iron
#

those are all the import i have

using TMPro;
using UnityEngine;
using UnityEngine.UIElements;

slender nymph
#

the last one is wrong

honest iron
#

import UI?

slender nymph
honest iron
#

UnityEngine.UI

#

OK

#

checking

#

ok, it worked

#

thank you:)

swift crag
#

note that a using directive lets you name something without fully qualifying it

#

it's not actually an "import" directive, where you have to include it to access something at all

#
using Foo.Bar;

...

var x = new Foo.Bar.Buz();
var y = new Buz();
#

it's just there for convenience's sake

#

without the using directive, I could still have written new Foo.Bar.Buz()

#

I just couldn't have written new Buz()

drowsy helm
#

Can anyone recommend a good resource for git patterns when working with another person? Right now we’re just sharing the asset dir without packages, but idk if that’ll scale well

grand snow
#

that will ignore things like the Library folder as that doesn't need to be comitted. If you leave out the other important folders your project will have serious issues...

drowsy helm
#

Ty!

faint agate
#

there is no for loop

void dawn
#

I need someone to teach me some stuff that i got stuck in my project

I don't want you to do it for me , I want you to teach me how to do it

You can dm me for more details but basically I need to add some stuff to my quake like fps game

1 voice line system , that works like duke nukem 3d were the character says a voice line depending on the situation

2 rigging enemies , I don't know why but I'm having a hard time adding animations to my enemies in the game , if you can help that would be great

3 gun movement, simple stuff I just want the gun to move when the player Walks and when the player shoots it

These are the main issues I'm having with the project right now , I would be very happy if you could help me

My dms are open

eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

faint agate
#

hello, ive adjusted the script to where its getting the current Selected Game Object, and vertical autoscrolling when at end. this script auto scrolls since im using keyboard to scroll. I dont want the auto scroll to happen on the last button going onto the next off screen but the button before the last one, so it starts auto scrolls on the one before last .
https://pastecode.io/s/5cszboon

#

ive been trying to make the current selected the one before the LastCheckedGameObject but cant figure it out

swift crag
#

i can't understand what you're talking about here

#

I dont want the auto scroll to happen on the last button going onto the next off screen

#

this in particular

#

is the problem that, when you switch from one menu to another, you see it smoothly scrolling back to the top of the second menu?

#

rather than snapping instantly to the top?

main jackal
faint agate
swift crag
#

Ah, so you need the scrolling to happen sooner

honest iron
#

Values is a list of enum values and i am trying to get a value by its name, tostring only return the type

public static SP getSPByName(string name)
{
foreach (SP i in Values)
if (name == i.ToString())
return i;
return null;
}

rich ice
#

temp variable names are cool and all but atleast keep them consistent guh

rich ice
honest iron
#

its always return null, i.ToString() return the type of the enum ,i need the value name

#

short for SkillPower

wintry quarry
#

But what is it

#

an enum? A class? A struct?

#

also what is Values

#

we need more context

honest iron
#

gimme a moment i'll get it

wintry quarry
#

return null seems not correct if it's an enum

swift crag
#

consider Enum.GetName

cosmic dagger
#

They probably want GetName but there's a lot of missing pieces here . . .

swift crag
#

you give it an enum type and an enum value, and it tells you the relevant name

thorn holly
swift crag
#

(and allocates, iirc, yummy)

honest iron
#
public class SoulPowers
{
    public static readonly SoulPowers NONE = new SoulPowers(0, null, null, null, null);
    public static readonly SoulPowers Fire = new SoulPowers(1, Skills.FIRE_KNOWLEDGE, SoulPowersAttacks.FIRE_PHOENIX, SoulPowersAttacks.FIRE_RUSH, SoulPowersAttacks.FIRE_FIRE_BLAST);
    public static readonly SoulPowers Ice = new SoulPowers(2, Skills.ICE_KNOWLEDGE, SoulPowersAttacks.ICE_ICICLES, SoulPowersAttacks.ICE_ICE_STARS, SoulPowersAttacks.ICE_ICEBERG);

    public int SoulPowersID { get; }
    public Skills SoulPowersSkill { get; }
    public SoulPowersAttacks[] AttacksList { get; }

    private SoulPowers(int soulPowersID, Skills soulPowersSkill, SoulPowersAttacks attack1, SoulPowersAttacks attack2, SoulPowersAttacks attack3)
    {
        SoulPowersID = soulPowersID;
        SoulPowersSkill = soulPowersSkill;
        AttacksList = new SoulPowersAttacks[] { attack1, attack2, attack3 };
    }

 
public static IEnumerable<SoulPowers> Values
    {
        get
        {
            yield return NONE;
            yield return Fire;
            yield return Ice;
        }
    }

    public static SoulPowers getSoulPowerByName(string name)
    {
        foreach (SoulPowers sp in Values)
            if (name == sp.ToString())
                return sp;
        return null;
    }
}
wintry quarry
#

not an enum

cosmic dagger
eternal falconBOT
wintry quarry
#

if you want ToString() to do somethjing special, you need to implement it @honest iron

#

the default ToString for a class will just print the type

honest iron
wintry quarry
#

you can do this with extension methods

#

but either way

#

if you are using a class

#

you must implement ToString

#

or another function that returns the string you want

swift crag
#

I was a little confused by how ToString was somehow producing the type name

#

that explains it

honest iron
wintry quarry
#

ok, well now you're in C#

honest iron
#

i know

#

that is why im here

nimble apex
#

somehow my scroll rect cant scroll to the bottom, theres always one element that is "out of window" , like u can drag the scroll to see it, but it will bounce back again

swift crag
#

yeah, C# enums are very basic

#

Java enums let you do some funnier s tuff

honest iron
#

for sure

polar acorn
#

C# enums are ints with hats

swift crag
#

if not, add one and then set it to control the vertical axis

#

(go for 'preferred' size)

nimble apex
#

nope 😭

swift crag
#

the Content object also needs a vertical layout group

#

set it to control child size and to not force expand children

honest iron
#

i think i'll just use switch for that

swift crag
#

together, these will:

  • make the Content object request enough space to show all of the children
  • resize the Content object based on how much space it wants
nimble apex
swift crag
#

make sure you set it to control child size

#

Force Expand will make it do...interesting stuff

nimble apex
#

and i havent checked use child scale once

swift crag
#

That looks correct

nimble apex
#

ty 👍

#

yep it worked

honest iron
#

is there a way to get sprite from assets without making pulic varible in the script?

rich ice
#

why?

honest iron
#

i am trying to set image(sprite) and there is too many images to add them all

#

i wanted to make class just for that, class the holds all the sprites and i can just get whatever i need from it

swift crag
#

i suppose that, if you have a huge number of assets with predictable names, you could load them from a Resources folder.

but I'm unclear on why you'd want to do this, instead of just assigning the sprites directly where they're needed

honest iron
#

i have a image that can be changed to 1 from 8 options, if i could just get the sprite from the without add it from unity i could just add it to an enum the related to this image

#

here an exapmle of what im tying to do

 public static readonly SoulPowers Ice = new SoulPowers(XXXX,2);

playerSoulPowerImage.sprite = SoulPowers.ICON

swift crag
#

so, for example, you might have an 8-by-100 sprite sheet

#

100 unique "things"

#

and each one has one of eight types

honest iron
#

i dont think is what i ment

#

XXXX is where i want to add the sprite from the assets

rich ice
#

have you tried an array?

honest iron
#

so i need to remove MonoBehaviour

#

which leads to error ; 'ObjectsImagesList' is missing the class attribute 'ExtensionOfNativeClass'!

#

im also looking for a better name for the classs

chrome garnet
#

I have a character prefab that contains an Animator with an AnimationController attached. Multiple GameObjects are instantiated using that prefab. Does each instantiated GameObject get their own unique copy of the Animator and AnimatorController when instantiated?

I ask because when I invoke an animation through GameObject.GetComponent<Animator>().Play("...") on one of the objects, the animation is playing on all prefab objects.

https://paste.mod.gg/lojzipnsahyy/5

eternal needle
wintry quarry
#

Use a paste site

#

!code

eternal falconBOT
chrome garnet
honest iron
#

i still need help

#

how can i add sprites from unity

public static class ImagesClass
{
    public static Sprite[] Weapons = new Sprite[8];
    public static Sprite[] SoulPowers = new Sprite[5];
}

#

i've added the script to a gameobject

honest iron
#

i want to reach the arries from everywhere in the project

rich adder
#

you don't need static here at all

#

use a singleton

honest iron
#

whats that

chrome garnet
rich adder
#

most important can make the fields regular ones that can be used in unity inspector (drag n drop) references

faint agate
honest iron
#

i might be wrong

#

still not expert with that

rich adder
#

you can't have static variables and expect them to show up / be linked in the inspector

#

if you're only sharing the same asset list of images through specific classes / objects, you could also use a scriptable object too

#

You must've misread what singleton is then

acoustic belfry
#

hey, how i can make that i have to wait till an animation ends to do x thing. For example, when my enemy gets out of bullets, it has to reload, wich displays the reloading animation and then returns the bullets to it original amount. How i can archive the wait?

rich adder
acoustic belfry
honest iron
sonic hull
#

use an animation event would be the simplest way

acoustic belfry
#

this is the script btw

    {
        if (balas > 0)
        {
            GameObject nuevoProyectil = Instantiate(proyectil, proyectilposition.position, Quaternion.identity);
            Vector3 direccion = (objetivo.position - proyectilposition.position).normalized;
            Rigidbody2D rb = nuevoProyectil.GetComponent<Rigidbody2D>();
            if (rb != null)
            {
                rb.linearVelocity = direccion * bulletspeed; // Ajusta la velocidad según sea necesario
            }

            balas--;
        }
        else
        {
            //Here its the reload thing
        }
    }```
rich adder
#

animation event is indeed the simplest, just has 1 major drawback is being aware of transitions could skip the key so pay attention to those

rich adder
acoustic belfry
#

i mean cuz its 2D, and every animation in the animator i have set all transition and stuff to 0

rich adder
honest iron
#

1 sec

rich adder
acoustic belfry
honest iron
#

4 for now

#

might be more in the future

acoustic belfry
#

then how i do it, cuz i need to have the transition set to zero in the animator

#

or so i thought

honest iron
#

i didnt even added all the images

public class ImageClass : MonoBehaviour
{
public Sprite[] Weapons = new Sprite[8];
public Sprite[] SoulPowers = new Sprite[5];
}

there will be more

sonic hull
#

the meaning is that, for example, if your enemy's roloading aniamtion was interrupted by a hurt animation or other stuff, the reloading success event will never be triggered actually

rich adder
#

then do the Awake Instance assignment as shown in the links I snent
you can easily access
ImageResources .Instance.Weapons

sonic hull
#

and you need other game logic to help you with that, such as a repeat reloading mechanic or sth on the enemy ai

acoustic belfry
#

the idea was that the reloading overrider all kind of animation, but the idea of restarting the reload doesn't sound too bad

#

im pretty noob in the animation part btw, that's why i rather to let it zero, as i saw that works for 2D stuff

sonic hull
#

oki, it all depends on how you design it

rich adder
honest iron
#

im testing if it works

rich adder
#

I didn't send the whole thing you still have to assign the Instance to itself
(#💻┃code-beginner message second link shows exactly how to write it)

#

it was example

#

I'm not here to write the entire thing for you lol

acoustic belfry
rich adder
rustic stag
#

Hello I was wondering if anyone can help me (or at least just explain to me) how to make it so you can deactivate certain game objects so its not able to be able to move when the camera isnt focused on it. I'm trying to make it so only one of my game objects moves/is able to be controlled by the player when the camera is focused on it. I have my code for my camera and code for each vehicle/player object if that would be helpful. (hopefully this makes sense)

wintry quarry
#

When you "deselect" the object, disable its movement script.

When you select the object, enable it

rich adder
# acoustic belfry btw what u meant with the state w/ bool?
Animator anim;
bool reloadingAnimation;
bool reloading;
private void Update(){
    if(reloading){
        reloadingAnimation = anim.GetCurrentAnimatorStateInfo(0).IsName("reloadAnimState");
    }
}
IEnumerator Reloading(){
    //reloading
    while (reloadingAnimation)
    {
        yield return null;
    }
    reloading = false;
    //done reloading
}```
obv dont know ur full setup so  prob missed something but roughly
acoustic belfry
rich adder
#

there is obv still StartCoroutine missing and all that

#

you probably can do the entire thing in update but its late my brain aint brainin

acoustic belfry
acoustic belfry
#

oh, ok

rich adder
#

you can easly call the coroutine when you start the reload process

#

if it needs to be in update put it behind a corutine variable or another bool

#

never StartCoroutine in update without those safety checks, aka start one every frame

acoustic belfry
#

i also have to play the animation, right?

rich adder
#

well yeah, the name of the state is what its looking for

acoustic belfry
#

i mean, add the script that activates it, the currentstateinfo will not do it for me

rustic stag
faint agate
#

I think the person who was about to help me went to sleep so im resending, ive adjusted the script to where its getting the current Selected Game Object, and vertical autoscrolling when at end. this script auto scrolls since im using keyboard to scroll. I dont want the auto scroll to happen on the last button going onto the next off screen but the button before the last one, so it starts auto scrolls on the one before last .
https://pastecode.io/s/5cszboon
Its a list of buttons and when I scroll one down from the final, the auto scroll happens. My goal is to have the auto scroll happen before going to the button off screen. I want the auto scroll to move or act when Im on 2nd to last button going onto the last, not when im on last going onto the button offscreen. basically I need the autoscroll to happen one button sooner

rich adder
# acoustic belfry nice

currentStateInfo just checks which one of those gray boxes you're in. Aka the States in animator

acoustic belfry
#

got it

wintry quarry
wintry quarry
eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

honest iron
#

but im still curious why is it better than creating instance of the class?

rustic stag
#

Thank you. I know very little about unity (did one full lesson about basic movement/ camera movement) Thank you though!

rich adder
#

putting the script on a gameobject literally IS the instance

wintry quarry
honest iron
#

ImageResources sss = new ImageResources();

rich adder
#

thats poco way of creation yes

#

MonoBehaviours don't work like that

#

when put put MonoBehaviour script on gameobject that creates the instance

#

then you're just setting the current one you got on that object as the static variable to hold it

acoustic belfry
#

???

{
    if (balas > 0)
        {
            GameObject nuevoProyectil = Instantiate(proyectil, proyectilposition.position, Quaternion.identity);
            Vector3 direccion = (objetivo.position - proyectilposition.position).normalized;
            Rigidbody2D rb = nuevoProyectil.GetComponent<Rigidbody2D>();
            if (rb != null)
            {
                rb.linearVelocity = direccion * bulletspeed; // Ajusta la velocidad según sea necesario
            }

            balas--;
        }
        else
        {
            animator.Play("Base Layer.MortemRifleReload");
            reload = true;
            StartCoroutine(Reload());
        }```
rich adder
rich adder
#

what is on it own?

acoustic belfry
#

the state

#

its the state of shooting

rich adder
#

anyway just in case you can docs if(reload) return; animator.Play("Base Layer.MortemRifleReload"); reload = true; StartCoroutine(Reload());

#

just set it back to false in coroutine and ur golden

acoustic belfry
#

hey btw, this means for default, reload and reloadanimation are false, right?

rich adder
acoustic belfry
honest iron
#

idk, i still need to get instance of the class whenever i want to use it, i was looking for a way to just get from it without instance(static)

acoustic belfry
#

what i mean is, i only have to do this in the shooting area

#
        {
            reload = true;
        }```
rich adder
acoustic belfry
#

...hey...
what diferences using booleans for ifes, and spawning methods?

rich adder
#

spawning entire voids?

acoustic belfry
#

for example, what diferences this

        {
            bullettimer -= Time.deltaTime;

            if (bullettimer <= 0)
            {
                bullettimer = firingspeed;
                disparar();
            }
        }```
rich adder
#

those are called functions / methods not voids
void is a return value for methods

acoustic belfry
#

from this

        {
            bullettimer -= Time.deltaTime;

            if (bullettimer <= 0)
            {
                bullettimer = firingspeed;
                disparar = true;
            }
        }```
#

and make it an if scenario instead of a method

rich adder
#

bool and method have different purposes

acoustic belfry
#

i mean, they work completely different...but their....purposes...mmm

rich adder
honest iron
#

nvm i guess i'll leave it this way for now

#

thank you for helping me

rich adder
honest iron
#

sorry

rich adder
#

if its working why is not good

honest iron
#

OCD lol

rich adder
#

just want to make sure you know whats happening in that code and why yours wasn't fit for unity

acoustic belfry
honest iron
#

im used for xxxx.ttt here is xxx.yyy.zzz

rich adder
honest iron
#

yeah, im sill new to unity

rich adder
acoustic belfry
#

like, "i did x thing in the worst way possible"

#

like the informatic meme of the cow walking with it udders explaining my exact issue

rich adder
# honest iron yeah, im sill new to unity

Unity cannot use Static variables in the inspector, nor can you put a static class on a gameobject, the only way you'd be able to assign those images is doing a Resources.Load fill or some other gameobject with serialized fields to pass those to static class.. At that point you mind as well skip the middle man gameoject and keep them on an actual gameobject that has component to serves them, since they can be easily linked in inspector this way

normal turret
#

What is the best way to tackle slope movement for a 2D game

#

Because in some games the character moves flawlessly on slopes but I'm having a lot of issues with that

rich adder
#

anything else is extra unnecessary worry

#

as long as you know..just dont make the code unreadable to you , and possibly others that you might need help from

rich adder
normal turret
#

Like moving at an angle or maybe not being able to move at a max-angle

#

Basic slope movements, I tried before and haven't got far...I'd love to get that out of the way soon

rich adder
#

was more talking about this

I'm having a lot of issues with that

#

what issues exactly? no one can help without knowing

normal turret
#

I have these slopes for example...I want my character to move on it without sliding or slowing down...

rich adder
#

ahh trig math here we goo

normal turret
#

I guess "slope-bounce" also is another problem with that

#

Because if I run down I guess my character doesn't stick to the surface

normal turret
#

Cosined by me

#

I could go on a tangent with this

rich adder
#

might want to raycast to get the slope angle then adjust your velocity / direction accordingly

normal turret
#

Should I keep the slope method seperate or can I do it all in the ground-check...?

#

Since I'm using tilesets, and it's all mostly one layer

rich adder
#

I haven't messed with Rigidbodies based controllers fully, but for CC I had it skipping slopes and thats what I did

rich adder
#

its just looks for colliders

normal turret
#

Oh ok nice, kind of like a ground check or wall check

rich adder
#

and their normal compared to Vup

normal turret
#

I just have to figure out the deal with slopes, I'll try working on that soon

rich adder
#

if you have raycast for ground, use the same ray
look for hit.normal

acoustic belfry
#

hey, this is not an issue i have, just an interesting thing i had in mind. Its a bad idea to mess with friction? i mean, i was thinking for make the always desired "m o m e n t u m", make that when i press a button to move the player, disable it friction, making it well, speed up in slopes and etc, and when the player releases the move buttons, for 2 seconds delays then it regains it friction. It may work, or bad idea?

acoustic belfry
rich adder
acoustic belfry
#

but sure, its not a big big deal, it just that it was pretty xd

rich adder
#

I find it good to take a break from the same project once in a while

acoustic belfry
#

sounds fair

rich adder
#

tf. someone just spammed your tag and prob got yeeted lol

faint agate
#

seen u guys were helping someone else, thought id ask now but ive adjusted the script to where its getting the current Selected Game Object, and vertical autoscrolling when at end. this script auto scrolls since im using keyboard to scroll. I dont want the auto scroll to happen on the last button going onto the next off screen but the button before the last one, so it starts auto scrolls on the one before last .
https://pastecode.io/s/5cszboon
Its a list of buttons and when I scroll one down from the final, the auto scroll happens. My goal is to have the auto scroll happen before going to the button off screen. I want the auto scroll to move or act when Im on 2nd to last button going onto the last, not when im on last going onto the button offscreen. basically I need the autoscroll to happen one button sooner

honest iron
#

since im not sure i have to ask

#

is its alright to give a single gameobject planty of scripts

rich adder
#

generally its okay as long as you don't mind the clutter

honest iron
#

like, player(gameobject) get scripts for movement, actions, attacks, inventory,skills, ect...

#

ok

#

tnx

muted pawn
#

wtf Im on mobile discord rn and I tried to send smth and my discord got fucked i tried closing it and it just spammed my message 100 times?!

#

sry for the spam tag on whoever it was, I thought I was gone forever 😭😭

rich ice
rich ice
final trellis
#
/*
if (card is a DamageCard)
{
    do stuff
}
*/

how would i do something like this?
card is an instance of the Card abstract class, and DamageCard inherets it

#

theres other card types that dont do damage, so i want to check to see if the card field contains a DamageCard

final trellis
#

wait is my psuedocode just like actually how you do it?? 😭

rich adder
#

just add a variable after DamageCard to do stuff with it
if (card is DamageCard damageCard)

wintry quarry
#
if (card is DamageCard dc) {
  Debug.Log("Damage amount is " + dc.Damage);
}```
final trellis
#

lmaoo

#

thats actually crazy 😭

wintry quarry
#

That being said it's... sort of an antipattern

#

Depending on the context

final trellis
#

wdym?

wintry quarry
#

Like, you should generally rely on polymorphism to get different behaviors from different subclasses

#

Abstract or virtual methods or properties. That sort of thing

final trellis
#

eh, thats prob fair but im makin a gamejam game so im tryna not spend too much time on certain things, ill keep that in mind tho when i do something that needs somethin like this in the future tho

sand heath
#

it does give a very nice and responsive control

#

I stop adding friction when moving and add it when not

thorn holly
thorn holly
#

Actually that example I gave is really bad since unity handles collisions and you can get a reference to whatever you collided with

#

Though you’d still have to check if it’s an enemy so ig it still works

sand heath
thorn holly
#

That too

sand heath
#

the way you phrase it makes it sound like you're working with roblox ?

thorn holly
#

Java swing 😭

sand heath
#

no clue what that is lmao

thorn holly
#

Its a Java library made for little pop ups like “enter your age” and such

#

Thought it’d be fun to make a game using it

#

It’s not

stuck seal
#

im about to put my head through a wall trying to implement the new action map, can anyone help me understand how im supposed to connect it to my character and c# script?

im following every tutorial and just getting nonstop errors, and even chatgpt has no idea whats going on

thorn holly
rich adder
stuck seal
#

i did, but then i go to implement it into vector2 movements and it says it cant find my input map

stuck seal
#

i can just ask in input system though if theres a dedicated channel for that tho

#

i dont want to use the wrong place

sand heath
#

sounds like a code problem. your inputs are correct looking

#

either that or you forgot to put a player input component on the thing you're trying to control, but you wouldn't get errors without doing that.. I think

rich adder
#

player input component is unecessary if they generated the c# class

stuck seal
#

im doing some of this to connect it

#

can you explain more @nav ? then how am i supposed to implement it to my character controller? or is that even necessary?

rich adder
stuck seal
rich adder
stuck seal
#

im sorry - im super new to this but im a coder by profession, so i just want to actually LEARN the code instead of downloading a controller

wintry quarry
stuck seal
#

i guess im confused what you mean by the asset

rich adder
thorn holly
stuck seal
#

you talking about this?

rich adder
thorn holly
tropic smelt
#

I don't know if this is the correct channel, but does anyone know why this character is in the scene and how to get rid of him?

thorn holly
honest iron
#

is there a way to link gameobject to an Instance(class) from the script?

thorn holly
honest iron
#

lets say that i have 10 items (Instance) i want to give every gameobject one item, and if i click that gameobject i can use this item

wintry quarry
#

That's very vague

#

What does it mean to "give a GameObject an item"

#

Are you talking about attaching components?

wintry quarry
#

Then it's very unclear what you mean

honest iron
#

let me find another way to explin

#

i have skills, i create gameobject for every skill, every skill has an Instance, when i press that skill i want to see more infomation from that Instance, but to do that i need to find the Instance that belong to the skill

thorn holly
honest iron
#

is there a way to add that Instance to the gameobject so i wont have to find it every time i want to

sand heath
thorn holly
#

Instance of a diff GameObject?

honest iron
#

List<Skill>[] Skills = new List<Skill>[5]; , Instance of skill

thorn holly
#

Okay so you have a list of the Skill base class

wintry quarry
honest iron
sand heath
honest iron
#

the gameobject are, yes

wintry quarry
thorn holly
#

Why can’t the subclass skill script just be a component of the ui element

runic remnant
#

Hello everyone, im new in C# and unity, and im just trying it out for fun, and to make games for hobbie, do you have any recomendation for a starting first game as begginer like me? (btw i can do 2d or 3d art, but ill prefered 2d) (sorry for interrupting just like that)

eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

sand heath
honest iron
#

let me try explin what i want to do in another way

thorn holly
honest iron
#
gameobj.add(s1);```

when gameobj is clicked 

public void func(){
gameobj.getSkill()
}


something like that
sand heath
thorn holly
#

Yes yes ai can explain coding concepts very well I should’ve specified

#

Don’t have ai generate your code

thorn holly
#

Oh

sand heath
#

I mean using AI search to find human written articles, videos, documentation related to the topics you're interested in

#

that way you're much more likely to actually learn from something trustworthy

thorn holly
#

Ah I see what you mean

rich adder
#

does Skill do anything?

honest iron
wintry quarry