#๐ปโcode-beginner
1 messages ยท Page 527 of 1
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "Move", menuName = "Pokemon/Create a new move")]
public class MoveBase : ScriptableObject
{
[SerializeField] string name;
[TextArea]
[SerializeField] string description;
[SerializeField] PokemonType type;
[SerializeField] int power;
[SerializeField] int accuracy;
[SerializeField] int pp;
public string Name {
get { return name; }
}
public string Description {
get { return description; }
}
public PokemonType Type {
get { return type; }
}
public int Power {
get { return power; }
}
public int Accuracy {
get { return accuracy; }
}
public int PP {
get { return pp; }
}
}
I have this to set up the moves
how do you plan on calling these moves
for the animation or general?
in general, because you could store animations anywhere
make another SO or mapping class
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I use this base to call it
did you google "animations on scriptable objects". it will give you some results
nahh don't mix them
seperation of concerns
make another SO for example that maps everything
someothing like this cs [CreateAssetMenu(fileName = "MoveAnimationMapping", menuName = "Pokemon/Create Move Animation Mapping")] public class MoveAnimationMapping : ScriptableObject { [System.Serializable] public class MoveAnimationPair { public MoveBase move; public AnimationClip animation; }
[SerializeField] private List<MoveAnimationPair> moveAnimationPairs;
private Dictionary<MoveBase, AnimationClip> moveToAnimationMap;
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I tried this but the animation doesn't play
private void OnEnable()
{
moveToAnimationMap = new Dictionary<MoveBase, AnimationClip>();
foreach (var pair in moveAnimationPairs)
{
if (pair.move != null && pair.animation != null)
moveToAnimationMap[pair.move] = pair.animation;
}
}
public AnimationClip GetAnimationForMove(MoveBase move)
{
moveToAnimationMap.TryGetValue(move, out var animation);
return animation;
}```
I have a battleunit for controlling all the animations tho
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
public class BattleUnit : MonoBehaviour
{
[SerializeField] PokemonBase _base;
[SerializeField] int level;
[SerializeField] bool isPlayerUnit;
public Pokemon Pokemon { get; set; }
Image image;
Vector3 originalPos;
private void Awake()
{
image = GetComponent<Image>();
originalPos = image.transform.localPosition;
}
public void Setup()
{
// Instantiate a new Pokemon and assign it to the Pokemon property
Pokemon = new Pokemon(_base, level);
if (isPlayerUnit)
image.sprite = Pokemon.Base.BackSprite;
else
image.sprite = Pokemon.Base.FrontSprite;
PlayEnterAnimation();
}
public void PlayEnterAnimation()
{
if (isPlayerUnit)
image.transform.localPosition = new Vector3(-117f, originalPos.y);
else
image.transform.localPosition = new Vector3(117f, originalPos.y);
image.transform.DOLocalMoveX(originalPos.x, 1f);
}
public void PlayFaintAnimation()
{
var sequence = DOTween.Sequence();
sequence.Append(image.transform.DOLocalMoveY(originalPos.y -48f, 0.5f));
sequence.Join(image.DOFade(0f, 0.5f));
}
}
hows that relevant to what I sent ?
no it isn't but I am showing what I have done so you can get a better idea
more or less I get what you're going for, hence the suggested code I sent
public void PlayMoveAnimation(AnimationClip moveAnimation)
{
if (animator && moveAnimation)
{
animator.Play(moveAnimation.name); // Play the provided animation
}
I had added this
the whole thing I sent associates clips with moves
to use its easy
[SerializeField] private MoveAnimationMapping animationMapping;
[SerializeField] private Animator animator;
public void ExecuteMove(MoveBase move)
{
AnimationClip animation = animationMapping.GetAnimationForMove(move);
if (animation != null)
{
animator.Play(animation.name);
}
else
{
Debug.LogWarning($"No animation found for move: {move.Name}");
}
}```
ok let me try it out
mapping SO class
testing script
@buoyant finch
actually you probably want to pass the clip itself not the name, but you get the point
Animator.Play plays a Animator state not an Animation clip
not really because op made exactly the same mistake
animator.Play(moveAnimation.name); // Play the provided animation
here fixed version
https://hatebin.com/vacctjnwnw
wait no..
Animator.Play takes in a string
https://docs.unity3d.com/ScriptReference/Animator.Play.html
is this supposed to be a new script btw?
the first one is a sepearate SO yes
yes which is a state name not a clip name
true true. Forgot which one to play clips without putting the states
legacy Animation iirc
oh okay.. i guess you need to add them in animator first
so yeah the clip name can be the animation state name if you drag the clips should be ok
so is it a problem with the script ?
don't just blindly copy it, analyze and try to understand what the first (important) class is doing
mapping
no no I found that the animatorclip is turned into a string
the animator uses strings as states yes, but the name has to match
if animation is called attack_01
then your Animator State has an attack_01 if you dragged that clip in animator window
public class MoveAnimationMapping : MonoBehaviour
{
// Example dictionary to map MoveBase to state names
private Dictionary<MoveBase, string> moveToStateNameMap = new Dictionary<MoveBase, string>();
public string GetAnimationStateNameForMove(MoveBase move)
{
return moveToStateNameMap.TryGetValue(move, out string stateName) ? stateName : null;
}
}
no idea why you changed it
is this true?
you clearly dont understand its purpose
the whole point is to grab a specific state/clip
why did you use string?
to return the name of the animation state (a string) instead of the animation clip.
meh if you have clips instead of typing all names it would be easier to put the clip
and more modular, you just have to make sure the AnimaClip NAME matches the Animator State its in
ye but the script has compilation errors
what is the error then
you can't just show the error without showing where its from
yes make it animation.name but make sure the Clip you added to Animator has the same name
they have to match. If you animation.name is called attack_01 then in the animator , make sure the gray box also says attack_01
hey guys, I think this might be my dumbest question yet, but I'm having trouble while using the law of cosines in order to find the length of a triangle side (passMaxDist).
in my example, I'm solving for A (passMaxDist), and I'm plugging in localAngle for Y, localDist for B, and longDist for C.
It makes zero sense to me why I'm getting NaN for these values, I'm using Mathf.Rad2Deg! :/ even when I try plugging in 0.05f for B, 135 for Y and 1.4 for C, it just shits the bed and gives me NaN. Any help would be greatly appreciated.
break the statement down into it's constituent parts. Debugging 101
but I will have to do it for multiple moves
what?
If you read my message again, you'll see that I recommend using a render texture, not the other option.
the animation is happening but I need it to occur only when the move is selected in the move selector
so im no expert but I think, Cos/Sin functions want radians not degrees, might want to get rid of Rad2Deg
so you probably want Mathf.Deg2Rad at some point there
NaN might be causing of squaring possibly a negative ?
that clears nothing about my confusion, you assume I know what you touched and didn't touch. Or whatever. I'm not psychic
ok wait a moment
I am talking about this the move/animation plays in the beginning I want it to play only when the specific move is selected as you see that when I use scratch the animation doesn't play how to fix it?
did you you use the code I sent? retrieve the animation paired to the moves. let the animator play
without the paired moves only the animator component
this one
what am I looking at
the animator only without the paired moves
there is no difference
and how am i suppoed to know you setup the animator and the moves/pairs correctly ?
you just showed a video, and not like you know..the setup?
ok lemme show you
make a thread while you're at it so its not flooded channel
how do I get the transform of the current active camera
Get the current active camera then access the wanted component using the available property (transform in your case)
Hello! I'm new here, could you help me wiht Time.timeScale? I heared that it's bar practice to change it from several peaople, but I didn't find any good points other than "you may want not all objects to be affected" about it. I wan't to do slowdown in my game, and after some research I believe it's ok to change it. Do you have some links to articles may be about it or just suggestions/advice?
Was there an error?
nothing wrong with changing timescale as long as you're aware that anything frame-dependant will be affected
yeah theres no reference
object reference not set to instance of object
You'll need to elaborate on what you're trying to do else I'm unsure of your environment, hierarchy, scope etc.
i am new to this so I dont know a lot but I have 2 cameras and i am making a parallax background that moves based on camera position, but it stops working when i switch cameras
just make a Camera reference directly in the inspector and plug them in
dont bother with those static props from Camera component
What stops working? Camera movement, parallax, crash etc?
parallax
btw, the parallax background is child of main camera
I'm trying to get the player to read a float from an xml file. This system works, but only for non-float falues, as of right now. What can I do to get this working, without changing the xml file?
Player class --> https://hastebin.com/share/wafonifule.csharp
Defaults (DefaultJrlGameObject class) --> https://hastebin.com/share/amomadeniz.csharp
MovementVariants.xml
<MovementVariants>
<HorizontalMoveAccel>0.2</HorizontalMoveAccel>
<WalkSpeed>5</WalkSpeed>
</MovementVariants>
Error: FormatException: Input string was not in a correct format.
(repost due to no reaction/response)
but main camera only has cinemachinebrain and the other one have cinemachinevirtualcamera
I want to move background based on position of current active camera
hello do you know why my character do that ? its happening when my character don't have rotation restriction
so whats happening instead?
log the characters position or every frame, or log the distance travelled since last frame (save position in a variable, log distance from current pos to that variable as a distance in debug). It looks like the camera tries to move towards some spot a bit away then not
It would be useful to tell us how you're swinging about
it works until the camera switches
okay what do you mean "camera switches" I'm not in your setup. Idk what you have so far
you have to show people your setup or else they cannot understand
Looks like you're teleporting to an incorrect position
ok i share you the code https://hatebin.com/empsuuhifk
i change priority of cinemachine cameras
so what happens after that, what stops working ?
you already have the cinemachine brain, you don't need Camera.current , what you need that for?
the camera switches correctly but the parallax background stops moving
idk
it work now but I use player velocity instead of camera transform
to move background
then you need it make it follow the main camera not the virtual camera if you switch them
Cinemachine brain always tells you which virtual camera is active
oo okay
and cinemachine brain will always follow the virtual camera active
ok ty!
hey guys anyone knows any tutrial on making first couple games? i rageuninstaled unity becouse all the tutrials gave me sintax errors for code and i couldnt figure out how to fix them since im new to unity...
!learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
start with the paths, like Essentials -> Junior Programmer etc.
its a slow steady start but will get you setup
Didn't cross your mind to ask the problem here?
i rage quit since it just made me so mad smashed my pc... fixed it back and reinstaled ๐
don't use random youtube vids, follow the structured courses from Unity Learn
and read your errors
as i pointed out in the first channel you posted this in, errors for obsolete code will tell you what to use instead
Hello. I have this task assigment where I need to make an object go up and down. The code works well, but I am uncertain about a thing:
For example, I have maxHeight = 10 and minHeight = -1, and my object starts at y = 4.5. Why does it go 10 units instead of y = 10 and why doesn't go to y = -1 and stops at y =4.5?
... Im actualy not someone you would think as a programmer... Im a chad... i mean not realy im 2 nice of a guy but my friends said i am one so...
๐
i lack patiance but im sick of having bosses who get on my nerves so i want to get into coding
or game dev
yeah ok please don't bring this here
yeah we don't need this moronic "chad vs incel" energy bullshit here
cringe
I had lack of patiance since discord didnt let me login as well...
if you lack patience then coding isn't for you, find another hobby
transform.position is the global position. is it maybe at 0,0 relative to a parent?
Well i need to better that aspect as well dont i ๐
if you lack patience then projects aren't for you, frankly.
projects take time. you will run into issues and roadblocks, and you'll have to solve them one by one. with help, sure, but you'll still have to do the work
so unity is c# code mainly?
you're most likely looking at the object's position in the inspector which is relative to the parent. but transform.position is relative to the world
complaining about it to random people on the internet won't help. Just do the thing and thats that, have an ethic of work
i want that the chatacter follow the line's angle
c# entirely
there's a visual scripting system that's a layer on top of c# though
so let's say that I have the object above y = 10, will it go crazy if it starts from above 10?
but best to do c#? visual scripting would limit my learnng would it not?
nvm, I found the answer
you can use localPosition instead for the local position
if the object is above 10 on the world Y axis then it will change direction, it wouldn't "go crazy"
it wouldn't limit your learning per se, but most people use c# so you'll be able to find better resources for it than visual scripting.
if you learn textual coding it'll also be a foundation for other coding
ive talked about this before one sec
unless of course the speed is so high that it stays above that position for longer than 1 frame ๐
by "going crazy" I mean that it will look like it's flickering because it's trying to go up or down
@lapis veldt You may find Mathf.PingPong useful if you want it to go back and fourth forever
Oh i used to be decent artist when i was kid.. sorry for asking 2 many qestions maybe but is it recomended to learn to make my asets on photoshop on the side or somthing else would be better?
try reading down from here #๐ปโunity-talk message @true parrot
but yeah, transform.localPosition.y did the job
whatever works for you. there's no restriction
as long as unity can import it, you can use it for unity
I wouldnt even worry about making assets in the learning/beginning phases of coding
ok got the ide thx
right and this is because you were confusing the position shown in the inspector (which is the localPosition and relative to the parent) with the transform.position (which is relative to the world not the parent)
I kinda need to use what the teacher showed us, since I still to learn trigonometry stuff and I don't want to have trouble with another teacher
understood, thanks 
its just art part is easyer for me then coding so maybe im trying to make excuses to avoid my weaker points
the least amount of graphics to deal with is easier, the GUI only adds extra complexity noise to learning code
ofc its always fun in unity to see stuff move around with a few lines but if you're absolute beginner its better learning how to even do simple arithmetic in code so basic c#, or learn the built in types first at least
public void OnPointerEnter(PointerEventData eventData)
{
if (!eventData.pointerEnter.CompareTag("Player")) return;
Debug.Log("OK");
}
How do I detect a trigger for a UI element
can someone hel me plz
This does not work
My net is sooo bad its going to test my patiance XD
wdym by "detect a trigger for a UI element"? because this is for the pointer entering the object, not a player object
and UI objects shouldn't have physics objects like trigger colliders
do you have the EventSystem object/component ?
if you want to use the EventSystem on colliders you need a Physics Raycaster on the camera
So its recomended to go trught this : https://learn.unity.com/pathway/unity-essentials Before i can understand most things?
yes @true parrot
So basically I have a UI element following the mouse when I click a card in the player's hand. And I want to detect if that UI element (which has the Player tag) is "colliding" with the other element
Ok thx a bunch ๐ sorry for being this random ๐
this seriously sounds like an XY Problem
You can see that there's the black image which wants to check if the low-alpha image is hovering over it
I could make a static boolean flag when the card is selected and detect the mouse hover, but I thought it would be nicer if I could detect the tag name of the object
you can just raycast from the EventSystem too, well it already does but you can retrieve info on what is cursor over
Can you elaborate?
EventSystem holds PointerData like what object its over
you can use graphics raycaster
Okay thanks
this should've worked fine btw. it just needs each black image to have the script or a parent target raycast
https://hatebin.com/empsuuhifk Hello, my character make this when there is no restriction in the rotation plz help me
don't crosspost
stick to 1 channel
pause the game when it start freaking out and see whats happening in scene view, like the anchors etc
hi, im making a top down rpg game similar to that of undertale. what is an efficient/effective way to manage/save/set a lot of bools to check if the player did some sort of action and change character dialogue according to the value of those bools? (i.e, a player chose to insult a character, next time they open the game the character is still bitter about them being insulted)
i thought about making a giant list of flags and checking values from there similar to how undertale did it (https://tomat.dev/undertale/flags) but i do not know how/when i would check these bools. undertale uses a switch statement with thousands of cases meaning it can check the bools there as all the dialogue is hard-coded in that script. for my game, i use a singular script which displays dialogue based on inputted dialogue objects. i can share my script if needed
i see that the line is not constant, maybe this is the problem
i use a distant Joint
quite possiblity, I use a different method, havent tried Distance component myself, i used spring
what is spring ?
spring joint
okay i will try
mine is a diff style though , i can go up or down
I am trying to take a slice of a sprite for further use through code, and so far all the TestBlock objects have no sprite being rendered (None (Sprite)) when I run the project.
I suspected it's something wrong with how I run the function, but after double checking, it seems fine. I believe the issue has to do with how I try to get the asset but I'm not sure.
Please ping on reply.
Screenshot #1 - TestStoneTileTileset.png
Screenshot #2 - Graphics folder (Assets -> Graphics -> ...) and it's contents
DefaultJrlGameObject -> https://hastebin.com/share/ufacologid.csharp
TestBlock -> https://hastebin.com/share/qewepilomu.csharp
I want to make the same effect
you can do it I believe
can someone help me with this little problem i got?
If it's code related, do share
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEditor;
using UnityEngine;
public class Elevator_script : MonoBehaviour
{
public Transform Player;
public Transform Switch;
public Transform DownPos;
public Transform UpPos;
public bool ElevatorIsGrounded;
public float speed;
void Start()
{
ElevatorIsGrounded = false;
}
void Update()
{
StartElevator();
}
void StartElevator()
{
if (Vector2.Distance(Player.position, Switch.position) < 0.5f && Input.GetKeyDown(KeyCode.E))
{
if (transform.position.y <= DownPos.position.y)
{
ElevatorIsGrounded = true;
}
else if (transform.position.y >= UpPos.position.y)
{
ElevatorIsGrounded = false;
}
}
if (ElevatorIsGrounded)
{
transform.position = Vector2.MoveTowards(transform.position, UpPos.position, speed * Time.deltaTime);
}
else
{
transform.position = Vector2.MoveTowards(transform.position, DownPos.position, speed * Time.deltaTime);
}
}
}
@timber tide look
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
i wrote this code to check if E is pressed then elevator moves
my entire camera system randomly stopped working and I ant find the lens ortho size on virtualcamera cinemachine anymore
it replaced by vertical fov
post the code properly how it was linked to you
use links for large code, like entire classes
ok
And probably clarify on the question
because your camera isnt set to orthographic
here you go
this is a code for an elevator if e is pressed at ground level it should go up and if it is pressed at the upper level it should go down
but it doesnt work i dont know why
i dont see any logs, start with that
Probably want to be using GetKey as well
GetKeyDown is one-time until you release I believe, while GetKey is continuously checking as it's held. But first you should learn how to debug your code in print statements via debug.log
ok doing that
KeyUp waits for release KeyDown is called the frame you squish down the button
alrighty
Actually, GetKeyDown looks fine here. I was thinking you held it for the elevator to move but it's just a switch.
Brains a little wired to the other input system right now
no problem
if the boolean is not getting triggered to true nor false, then one of the if statements is not getting called,
wait
isn't MoveTowards vector3 and not a Vector2 ๐ค
I added logs
when the game ran it game going to the down position never goes to up position even when i press e
hol up
sorry I was looking at the wrong one
no worries
well are the logs under the if statement ElevatorIsGrounded and or the else statement under it called?
the else statement
it continuously says Moving downwards
its skips the first if statement and goes directly towards the if else statement with the boolean
it cant detect the e im pressing
Did you log the input, because you have two conditions to go into your switch there
and are you actually close enough to the button?
i did right now it doesnt detect the e
im literally on top on the platform while pressing it
always split these up so they can be logged
Vector2.Distance(Player.position, Switch.position) < 0.5f && Input.GetKey(KeyCode.E
var distance = Vector2.Distance(Player.position, Switch.position);
var eKeyHeld = Input.GetKey(KeyCode.E)
Debug.Log($" distance is : {distance} and keyHeld {eKeyHeld}")
ok
if (Input.GetKeyDown(KeyCode.E)
{
Debug.Log("E Pressed")
if(Vector2.Distance(Player.position, Switch.position) < 0.5f)
{
Debug.Log("Distance Check")
if (transform.position.y <= DownPos.position.y)
{
ElevatorIsGrounded = true;
}
else if (transform.position.y >= UpPos.position.y)
{
ElevatorIsGrounded = false;
}
}
}
ill try changing the distance
can also debug the value so you know what numbers you need
Also worthwhile to learn how to use VS studio debugger so you can just use breakpoints
Visual Studio Studio
lel
YOO I FOUND THE PROBLEM
when checking Euclidean distance using one of the distance functions it checks the models pivot point when using a transform.position I believe (well it just checks the distance between 2 vectors but the vector it checks is the pivot point)
How does data persistence between sessions work on platforms like Unity Play, where there aren't any files downloaded and the game is played online? Does the save data just go on their server?
webgl you would use the built in datastorage of browser
unity has playerprefs but can also use via javascript interop
it would get stored in the usersbrowser not their server
Could someone help me real quick?
It's being a roadblock
how do you guys store your event system / other unity things you're only allowed one of like audio listener?
Unsure if this is a good place to ask or not TBH but:
Does anyone use the SteamWorks SteamManager script, and, have the issue where when stopping playmode, Steam says you're still playing the game?
Steamworks does this based on the running process, there's really no way around it. It doesn't harm anything and you won't have issues with starting play mode again, steam will just display that you're still running the game until the editor is closed
It seems to be causing issues with my controller only in editor tho. Where it completely takes prio over everything, and disables Unity from detecting it. On build, it works fine and I can swap between Keyboard + Mouse and Controller fine. But after first launch of the game in editor, the second time the controller is never detected.
How have you confirmed that has anything to do with steamworks? Also in the future ask about the thing you are actually having issues with rather than your assumed cause
Because if I disable Steam Works from launching inside of Unity completely/remove it from Unity, it works fine. So the assumption is Steamworks.
If it is caused by steamworks then ask whatever asset dev made the steamworks integration asset you're using (I'm just going to go ahead and assume that since you are asking about non-code issues in beginner code that you didn't use the steamworks sdk directly and are instead using some wrapper asset for it)
Im using the direct Steamworks/SteamManager that they provide. https://steamworks.github.io/steammanager/
Yeah so you're using Steamworks.NET, a third party asset that wraps the actual steamworks sdk for use in .net
hey so I am still a noobie at coding and I decided to make a flappy bird clone. I have added a rigid body to the player. I want it to have the same movement system as flappy bird. I have made a custom function called void OnJump there is 3 dots under On. did I do it wrong?
Put the mouse cursor on top of it and see what it says
no, it's just a warning that you haven't used the method yet
oh your right lol 
hi, im making a top down rpg game similar to that of undertale. what is an efficient/effective way to manage/save/set a lot of bools to check if the player did some sort of action and change character dialogue according to the value of those bools? (i.e, a player chose to insult a character, next time they open the game the character is still bitter about them being insulted)
i thought about making a giant list of flags and checking values from there similar to how undertale did it (https://tomat.dev/undertale/flags) but i do not know how/when i would check these bools. undertale uses a switch statement with thousands of cases meaning it can check the bools there as all the dialogue is hard-coded in that script. for my game, i use a singular script which displays dialogue based on inputted dialogue objects. i can share my script if needed (sorry for the repost)
Post what you're managing so far via paste site
sounds like you'll need some kind of GameManager to track flags.. and possibly some type of asset thats built for dialog.. and dialog trees..
https://www.youtube.com/watch?v=HVls6_srbNc&ab_channel=InfinityPBRโขMagicPigGames scriptable objects seem to come up frequently
(or some kind of event based system)
okay, here is the script that manages writing dialogue in my game
https://hatebin.com/wzutmkqjqp
and the script that manages displaying it
https://hatebin.com/aadtqsqtlm
if you see a type "DialogueObject" in my scripts just letting you know that it's a scriptable object that holds dialogue, a voice sfx, the dialogue speaker's name, and repsonses
whats ur biggest concern? like what part are you stuck on?
im just stuck on how im supposed to implement flags into this system that checks if a bool or smth else is true. and if it is, a new dialogue object replaces the current dialogue object
I wouldn't really say no to making a class for each type of character assuming you've only a handful of them. Having a base that shares some similarities would be ideal, leaving you with some room to hardcode some logic and events.
because doing something completely modular could be a nightmare if you're a beginner in how to organize a lot of this stuff.
Dialogue is actually quite a tricky subject and I even use some assets to now deal with it most of the time.
you could have a dictionary of flags and a singleton (game manager type script) that manages those flags..
such as setting a flag true, or setting on back to false..
FlagManager.Instance.SetFlag("InsultedNPC", true); for example
you could check the keys and swap dialog when u need.. (im just trying to think of something really simple)
ya, i've never made my own dialog system.. as its probably outside my skillset.. theres alot of good assets out there even if I don't use the entire asset it can really help to just peek at the code and see how its done in that specific asset
okay, but im confused on where i would check the keys? (or are you talking about using this in terms of what Mao said regarding a class for each type of character?)
sorry if this is wrong but are you saying that a possible solution could be to make a class for each one of my characters then hardcode what i want them to say based on what flags are true and what not then feed it to TypeWriterEffect? using this system i could then do what Spawn said about making a FlagManager probably
What would be the best way to indicate that all enemies in a given wave are defeated?
Iโm instantiating waves by putting enemies under an empty game object and storing them as prefabs inside a serialized field list
How can I make it so it falls down quicker? it feels very floaty.
Watch "FlappyBirdClone - SampleScene - Windows, Mac, Linux - Unity 2022.3.26f1_ DX11 2024-11-17 18-26-48" on Streamable.
on the rigidbody there are some options
change the gravity of either your scene or the rigidbody
i would not recommend to change the global gravity
I'm just displaying the options they could do, of course it would be better to change the gravity directly on the rigidbody if they want nothing else to be effected
my only suggestion was the flagmanager.. if its a singleton or a static class it'd exist thruout the entire game..
and could be accessible anywhere..
for example
// Set a flag
flagManager.instance.SetFlag("PlayerFinishedLevel1", true);
// Get a flag
bool hasPickedUpRifle = flagManager.instance.GetFlag("PlayerPickedUpRifle");```
as for the rest of the dialog system.. i don't have any useful commentary sorry
yup, I like to just add a negative force
// Simulate gravity manually
Vector3 simulatedGravity = new Vector3(0, -9.81f, 0);
rb.AddForce(simulatedGravity, ForceMode.Acceleration);```
tbf, i know alot of people, as well as myself, that thinks Unity's gravity is a bit floating everywhere.. soo I don't see anything wrong w/ cranking up the global gravity just a smidge ๐ค 10-11 makes everything feel a bit more grounded imo
if they choose to go this route, then they need to make sure this is done inside of FixedUpdate.
They also need to make sure to reset the Y velocity to 0 before adding their jump force if they want it to be consistent each time instead of fighting against gravity
๐ฏ no lies told..
also they need the rigidbodies gravity disabled if you implement artificial gravity unless they want it doubled
i lied.. i changed it to 10-11 i was over-estimating when looking at my own projects they usually hang out around -10 for gravity
https://www.youtube.com/watch?v=7KiK0Aqtmzc&ab_channel=BoardToBitsGames this video comes to mind everytime
simply a fallMultiplier
also, that supermario character feeling where u press the button quickly for a small jump and hold it for a long jump seems to make every platformer ive worked on feel much much better..
I agree. Having a fall multiplier, separate jump multiplier for press and hold, coyote time, and jump threshold (when landing to jump again) definitely makes the player feel more responsive . . .
I think there were some other mechanics I did as well, but I can't recall atm . . .
๐ฏ believe all 3 are some of the most important aspects of "feel-good" controllers
"buffered jump" is what i've seen that last mechanic called a few times and what i've named my own as well
Me because I know how to make a discord bot I will integrate it to tell me how many players are in the game
im trying to make my charakter jump but everytime i do the "if" code i get this message
this is how my code looks
You have a spelling error?
Did you look at the error in your code. Is it correct?
Among other things but that's the obvious thing that's underlined.
i dont think so
Did you check to make sure you typed it in correctly?
i copied everything from a tutorial viedeo
where?
The one that's underlined
You need to be 100% sure. If you don't think so, then go back and make sure it is 100% correct . . .
ohhhhhh
shit
ye i see it
lol
ok could swear i copied that bcs i had that problem for like 15 minutes and i retyped everything like 10 times
but maybe im just stupid
thx
huh now it falls like a rock
and the whenever i press space it doesnt do anything

did you attach the component
is this not the right syntax?
UnityEditor.DragAndDrop does not inherit from UnityEngine.Object therefore it cannot be used in FindOjbectsOfType
what are you even expecting it to find?
syntax is right, but it's semantically incorrect
wait does that mean UnityEditor has its own draganddrop thing?
i think i did
do you have your own class called DragAndDrop? if so, then the issue is that you have the UnityEditor namespace imported and it's using that rather than whatever yours is
Isnโt it supposed to be a list?
i think it can be either
but that was the right syntax for arrays, just wrong class* name
Oh lol
ohhh thx
there is no overload of FindObjectsOfType that returns a List, it only returns an array
oh, good to know
im assuming if you really wanted to youd use a for loop then and put them into a list manually?
there's also the ToList method if you really wanted a list
oh nice! the more you know
i dont think ive seen that method before
what happened to what you had before
angularVelocity is how fast something spins, you want linearVelocity to control how fast something moves
oh
have you added using UnityEngine;
no i havent
why didn't you just go back to check the tutorial
or yknow the code you posted here earlier
i didnt think of that
and the tutorial is 1 year old
the code doesnt 100 percent work
he just has "velocity"
right, that's somethign that changed with unity 6
i'd recommend using official tutorials instead of stuff that isn't kept updated !learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
It probably does for the stuff before Unity 6
oke
ye thats how the tutorial script looks like
i'm working on my first unity game, which is vr, i have a guy who's helping me but he does most of the coding (so basically everything) but i want to work on it too. i just don't know much. how do I learn to code?
there are beginner c# courses pinned in this channel. and the junior programmer pathway on the unity !learn site is a good place to learn how to use the engine's API. i recommend learning c# separately from unity first as you'll have an easier time with learning the unity specific stuff after taht
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
Once again, what you've written isn't what the tutorial has.
they're using unity 6
How to do camera switch from certain angle
- Move the camera's position and rotation.
- Swap/Toggle from one camera to another
Cinemachine package makes this pretty simple
does anyone know why my camera zooms into the body no matter where i move the camera? ask for screenshots of scripts if u need
thanks!
check your vcam settings
Must be something in your script, as the camera holder position changes drastically.
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hi everyone just checking to see if this is the right place to ask some coding questions
this or the other channels in the scripting section
I'm trying to dip my toes into character customization, starting from ground zero here. From what I've gleamed so far from some assets is that a character would have all possible options attached to them but only the ones being used are set active am I on the right path?
yea thats a common way to do it
Is this the simplest method? Wouldn't that limit me and the prefabs I can use to what's be made for the character avatar? and wouldn't that eventually create a lot of clutter?
simplest yea, also limited in that you now need prefabs which contain every possible option, yea.
you should first consider how much customization you'll actually have. if you arent having a ton of characters and unique customizations in the first place i wouldnt worry about it
Hi, i tried to make a script for check for the pointer for make my player sprite flip...and well
Technically it half-way works, cuz the player sprite flips, depending on where "the pointer" is in relation with it
...the issue is that it only reads the "pointer" as the center of the screen, and doesnt detect the mouse
what i did wrong?
You'll need to provide a bit more info and code.
ok
}
void FlipSpriteWithMouse()
{
if (Camera.main == null)
{
Debug.LogError("No se encontrรณ la cรกmara principal. Asegรบrate de que una cรกmara estรฉ etiquetada como 'MainCamera'.");
return;
}
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if (mousePosition.x > transform.position.x)
{
if (spriteRenderer != null)
spriteRenderer.flipX = false;
}
else if (mousePosition.x < transform.position.x)
{
if (spriteRenderer != null)
spriteRenderer.flipX = true;
}
}
}```
This is the (sprite flipping fragment of the) code
i strongly believe the rest of it is irrelevant
The idea is what depending where the mouse is, the player sprite would vertically flip, like if they were "watching" the mouse, and i think sorta does...But it only flips to face the center of the screen
it completely ignores the mouse
- Are you using an orthographic camera?
- Can you record a video of the issue?
Well, then it's kinda hard to help you, as it's not entirely clear what the issue is and what is the context of it.
well, the idea is this, this is a 2D game where the idea was that if the mouse pointer is on the right of the charatcer, the sprite would face right, and viceversa
but...it only does that, with the center of the screen
i hope that info helps a bit ;-;
Not sure I understand this part . . .
The only thing I can think of is that transform doesn't belong to the character and remains positioned somewhere else(close to the center of the screen).
its like the cursor were permanently on the center of the screen
i got lost
the transform thing is supossed to swap it...i think
As dlich mentioned, I would make sure you are using/checking the correct transform . . .
how that would look like?
Other than that we can't really help you without seeing what happens on the screen
maybe screen shots?
If you can take a screenshot you can probably record a video.
i mean, how i can record a vid?
the only way i know is Obs
wich is quite heavy
I'm not sure what you're asking here. The transform there needs to be positioned where the character does. Then it should work theoretically.
That. Yes.
Did you actually try and there was an issue?
it will lag like hell ;-;
i mean, every time i turn on Obs it lags a bit, and every time i turn on Unity it lags a bit
so by logic, they two turned on together would lag a lot
but i can give it a try i guess
Is there any reason this function would be running twice? (It is tied to an enemy script, and when that enemy script detects collision with the player, it runs this LoseALife function)
public void LoseALife()
{
if (hasShield == false)
{
lives--;
GameObject.Find("GameManager").GetComponent<GameManager>().Lives();
Debug.Log(lives);
} else if (hasShield == true)
{
//lose the shield
//no longer have a shield
}
if (lives == 0)
{
gameManager.GameOver();
Instantiate(explosion, transform.position, Quaternion.identity);
Destroy(this.gameObject);
}
The number of times a function runs would come down to the code that calls it.
This is the code I have that calls it. It should be called if this enemy gameobject collides with the player, but for some reason, it must be calling it twice. Im not sure why
private void OnTriggerEnter2D(Collider2D whatIHit)
{
if (whatIHit.tag == "Player")
{
//I hit the Player!
whatIHit.GetComponent<Player>().LoseALife();
Instantiate(explosion, transform.position, Quaternion.identity);
Destroy(this.gameObject);
} else if (whatIHit.tag == "Weapon")
{
//I am shot!
GameObject.Find("GameManager").GetComponent<GameManager>().EarnScore(5);
Instantiate(explosion, transform.position, Quaternion.identity);
Destroy(whatIHit.gameObject);
Destroy(this.gameObject);
}
}
The content of the function doesn't matter
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
If either of the objects involved in this interaction have multiple colliders that could be why
is it possible for the collision to be detecting twice?
Or is this unlikely?
only if there's more than one collider
hooly hecck apparently I had 2 ๐คฆโโ๏ธ
tysm
A bit + a bit = a bit. Logically. Though, this is complete speculation. You need to actually try and see...
Here is the vid. As you can see, the player is always facing the center of the camera, wich is not what i want to do (i also quickly moved to the oppositive side for prove that wasnt flipping due moving left or right). And i moved the cursor around to show that it doesnt follow the cursor
the idea is like this proyect i made in godot long ago
...wich for an strange reason now Obs frozen
So, it's not orienting itself to the "center of the screen", but rather to the center of the scene.
;-;
wat
i mean
no matter how many i move around the map, happens the same
It always faces one point in the scene
Which would make sense if transform in your code was some static object at that position.
this is the objetive
This is gonna make me seem really stupid but I just can't figure it out
I have an Image object in my canvas that I'm using to hold multiple different sprites (that is to say, it's setting itself to a different sprite depending on what data it's given).
It's not having any trouble changing sprites, but no matter which settings I toggle, the sprite always stretches to fill the entirety of the Image's Rect Transform space. I've tried preserving aspect ratio, setting it to native size, setting the source sprite's mesh type to Full Rect, and it still keeps stretching. I'm totally unsure how to fix this.
There are far too many images for it to be set to for editing them all to fit the same aspect ratio in photoshop to be a feasible option.
how i can make it face the cursor then?
Looks good, you going to do a wall jump?
thanks ;w;. But this is a discarded proyect in godot ;w;
But im trying to conver from there, to Unity
Oh I see, my bad.
and yes, its supossed to have dashs, double jumps, walljumps, etc
but now im struggling with only the sprite flipping ;-;
I've been meaning to try godot but been too focused with Unity trying to get my 3rd year out of the way
but thanks for ask :3
I tried Godot, is easier to use...but it lacks a lot of tutorials and stuff that might be usefull, and also my teacher said it can make errors and glitches when it exports. So thats why i moved to Unity
As I said, make sure the transform actually moves with the character. Do you not understand what your own code is doing or supposed to do?
50/50 ;-;
Godot brought our GOAT brackeys back though lol
but i mean
what do you mean with that?
the transform is on the sprite part
wich causes it to flip
if the mouse is higher, it flips to one side
Look, I don't know how to put it simpler than that. What exactly do you not understand?
;-; sorry. The exact way you want me to modify the code
Is it? Take a screenshot of where that script is in the scene?
What GameObject is the script assigned to?
Player
actually, the name of the player
Take a screenshot
but that's confidential till i finish it, due copyrights and etc
Of the scene
And take a screenshot of your camera component as well
camera component?
you mean what the camera has?
You'd need to learn some unity basics if you want to use the engine. gameObjects and components are 2 of the very most basic concepts in unity.
No
Components are components.
!learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
i was right, i strongly suck at names and descriptions
At this point, the transform is probably not the cause. You'll need to debug the issue, as I can't see anything else that could be wrong.
Well, share the camera component.
i didnt knew if you would need the ones that are hidden
i call those propeties ._. sorry
You're using a perspective camera, not an orthographic one
If you want to use a perspective camera, you'll need to make sure that you use the correct z coordinate in screen space to world space transformation
i what? really?
what would be the correct z coordenate?
i always thought it was on orthographic o-o
Look at your screenshot yourself. It says "perspective".
It would be the same as your character z in world space.
Modify for what purpose?
work like this
instead of this
hol on
i think i fix it
Did you set your camera to orthographic?
yep
And it still doesn't work?
what is the suggested way to handle sorting multiple overlay canvases that are all siblings? In my case, they are different UI tabs and I want the one clicked/dragged to be brought to the top. Reordering the transforms does not work since I believe canvases only sort with sort order? however there is already an order when all of them are on sort order 0, so not exactly sure why. Im trying to avoid setting the sort order since it would require each tab to know the sort order of the others
Sorting layer/order in layer are the best way.
How many such tabs are there? You could just run a for loop that numbers them all in the desired order whenever you need to
3 for now but there will be more when I add more UI tabs, and yeah I could easily do that but was just wondering if there was a way as simple as transform.SetAsLastSibling since that seems to not be working
Hierarchy order only matters within a canvas
figured
It doesn't control how different canvases interact
what decides the order when all are on sort order 0?
anyone else having package manager issues? its not connecting
The "tie breaker". Probably the ordering in some internal list, or an instance id or something. Nothing you can or should rely on
got it
is scripting define symbol in player setting automatically apply to assembly definition or i must add them manually to define constraint in the assembly definition asset ?
assign manually. scripting defines are per dll
So scripting defines is only for dll?
for creating dll's, yes. What do you think an asmdef does?
No i mean, does scripting defines only apply to script that is not in any assembly definition, or it also apply to script inside assembly definition ?
The scripting defines in the player settings
the scripting define in player setting is applied to the Assembly-CSharp dll creation only
Ah i see, so i must add the scripting defines again for each assembly definition right ?
yes, that is what I said
Okay thanks sorry i got a little confused there lol
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hey guys... I have been searching and still not convinced best way to approach this situation. I have the player bullet. But it only spawns when he shoots. But I need to get information about the bullet before it is spawned, and also update it everytime it change it stats, but I cant do it as it says null because of course it didnt spawn yet. How would you approach this ?
But I need to get information about the bullet before it is spawned
What kind of information? What do you mean by that?
and also update it everytime it change it stats
Update and change the stats of what?
but I cant do it as it says null because of course it didnt spawn yet
What "says null" What do you mean?
The bullet has a speed and damage it deals. While the game is running the player can updagre his bullet damage. That is coming from PlayerBullet script. I want to show the damage and speed on screen but when I try to fetch that information it says it cant get as the bullet doesnt exist. So before the game start even on the menu you should be able already to see the bullet damage for instance.
What does that have to do with the bullet? That sounds like information that should live on the player
So the bullet should know its damage not the player I guess no? Why the player would have that information if the damage is not the player damage, but the bullet damage itself?
Why the player would have that information
Because the player is the thing that levels up and the player is the source of bullets
it is "damage of bullets created by this player"
think of it that way
The bullet of course should know its damage, but that's something the player will assign to the bullet when the player spawns the bullet
it's not an intrinsic part of the bullet prefab
hmm.. what abouit these other variables I have inside the bullet script. that should then follow the same logic you are saying?
If they are actually things that are stats on the player they should be on the player
but really
you should wrap all this up in a class
or a struct
and slap a field of that type on both the player and the bullet
the player will hold the stats for what bullets it will spawn
and then you just copy it over to bullets as they spawn
hmm, I was trying to save the player script to have more information, but it seems like I would ned to do the way u are saying
Imagine:
public class Player {
public BulletStats bulletStats; // Stats for bullets this player will spawn
}```
void SpawnBullet() {
Bullet b = Instantiate(bulletPrefab);
b.stats = this.bulletStats;
}```
hmm.. so BulletStats I would create a new script for that appart of the Bullet script?
I don't really understand the question
BulletStats as you named, that is a script correct?
I just checked documentation that define constraint in assembly definition does not define symbol, instead it is a constraint that a symbol must/must not exist for unity to include that assembly definition (for example, unity won't compile that asmdef if a symbol does not exist). How do i define symbol for assembly definition ?
I also checked the documentation that custom symbol apply to the whole project, but i havent test if it also includes script inside assembly definition
Hello !! I have one question, is there anyone who has already made a graphical dialog system ? I would like to have some help !!!!
probably best to make a .rsp file
https://docs.unity3d.com/Manual/custom-scripting-symbols.html#asset
hello, i have some questions.
is there a much sense in making PlayerController not a monobehaviour?
Should i try to get rid of MonoBehaviours in places where it can be omitted. Like making a general MB script for player and inside make multiple others that do things? Or it's better to stick to MB for GameObject stuff and leave other for data and such?
What is a best practice for this kind of situations?
pseudoexample:
public class PlayerScript : MonoBehaviours{
PlayerController _controler;
void Awake(){
_controler = new PlayerController();
}
}
public class PlayerController{
public PlayerController(){
// here be code
}
}
It would be unusual if a player controller wouldn't need to use any monobehaviour methods but yes, if you have a class that doesn't need any of that and you don't need to handle it in the editor then it's usually better for it to not be a monobehaviour
it is completely up to how you want to architect the game, people have done both with success, or other options as well. It is probably easier in this specific case to just use MonoBehaviours since you are simply emulating a MonoBehaviour in the example (i.e Awake -> Constructor, probably Update -> PollInputs, FixedUpdate -> Simulate, etc, not too useful)
yeah it was gonna be something like that
i questioned this because i was once told that i use MB a bit too much and i saw that kind of implement in a video about zenject.
in my completely personal opinion, if you are working alone, you can pretty much just do whatever works for you, and therefore you are free to try new stuff out
some people like zenject and others dont, for example
at the end of the day, it's about creating something, and usually the means of doing so dont really matter that much (clearly demonstrated by many indie games)
stick with what you know until you can actually explain / analyze an issue with the approach. If that point never comes, then great
yeah, i do work alone but my intention is to get a job, so i try to at least look into things that is common in industry
big thanks for answers 
each studio has their own opinions as well, so the best way to prepare is to actually just be good at programming and have experience with many things
I need a bit of advice for a project I am working on. The project itself isn't difficult, it is mainly an interactable art gallery.
However, the project needs to support multiple languages. There needs to be a drop down where the user can select English, Korean, Japanese, or Chinese, and the entire app needs to swap its text to that.
What is the best way to go about something like this? My current prototype is a bit inefficient, but it has a Scriptable Object for each language, that contains a list of every word and sentence that is present in every item that has text, and when swapping languages, the system cycles through everything that has text, and replaces it.
It works, but I feel like it is extremely inefficient. Would anyone have advice or tips on how to tackle this please?
Unity does have a Localization package
I was not aware of that. I'll take a look, though for now, can you perhaps please provide me with the API for it?
thank you
using UnityEngine;
using System.Linq;
using System.Collections;
public class main : MonoBehaviour
{
IEnumerator seconds(){
yield return new WaitForSeconds(10);
}
void Start()
{
for (int i = 0; i < 5; i++)
{ StartCoroutine(seconds());
Debug.Log("salam");
}
}
}
in running screen string just appers 5 times in console without waiting
StartCoroutine(seconds());
the wait doesnt happen on the main thread
if you want to wait a second and print something
write it like this
void Start()
{
StartCoroutine(DoSomething());
}
IEnumerator DoSomething()
{
for (int i = 0; i < 5; i++)
{
yield return new WaitForSeconds(1f);
Debug.Log($"Salam: {i}");
}
}
yes, i am trying to make countdown system
yea then write the entire logic inside the coroutine
thanks for time
np ๐
Hey everyone. so i am making a mobile game, basically there is a circular boundary and there is a ball and a hitpad. At the start of the game the ball randomlys goes in some direction and your objective is to use the hitpad to keep the ball inside the cirlce and not let it hit the circle. Cool.
The thing is, I have made the bal have 0 zero gravity and i use force to propell it in some random direction at the start of the game and but there is a problem, at some angles the speed of the ball can increase weird. So on every 5 hits, i am increasing the speed of the ball by a bit (equal amount every 5 hits). and the max is 10 magnitude of velocity. but at some weird hits sometimes, the speed of the ball can increase drastically and at some hits it even decreases drastically, So for this i added some checks in Update but to no avail.
To give a better idea of how the game works I added a picture. Anyhelp would be really appreciated
here is my Update method and the way i am increasing the speed of the ball
https://pastebin.com/rYnerD0S ask me if anything more is needed
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I am failing to see where it should be doing it's main function - increasing the speed of the ball
it is being called in the OnCollision, the method called "IncreaseBallSpeed();"
{
// Increase the ball's speed slightly
ballRigidbody.velocity *= (1 + speedIncrease);
latestBallSpeed = ballRigidbody.velocity.magnitude;
Debug.Log("Last Ball speed was " + latestBallSpeed);
}```
i forgot to add it to the pastebin
I am personally not directly seeing the problem, but I can suggest you to go away from physics, I assume you are using standart Dynamic rigidbody?
you should propably Clamp lastKnownSpeed here
yes i am using dynamic rigidbody. I am sorry i might have worded my problem weirdly. So the thing that is happening is, on every 5 hits between "Ball" and "HitPad" i am increasing the speed of the ball by a bit (same amount every 5 hits) till it reaches a max speed after that it doesnt increase. Whats happening is that sometimes, the HitPad and Ball collides in a way (unintentionally/not same everytime) that the balls speed can either go from 4 (velocity magnitude) to 7 or from 7 to 4.
hello every on
my canva (gamecanvas ) start not showing any elements any one has face same problem?
have you fiddle around with physics material 2D?
honestly that won't be a true solution but setting bounciness to 1 and friction to 0 for everything might help
on the other hand I would rather make my own reflection method in OnCollisonEnter2D and use kinematic rigidbody, because not using physics for this kind of game looks like a way to go
yes i did try it, infact what i did was remove the material all together, and instead of relying on physics for bounces, i tried to calculate the angle of normal and then use transform.translate to move the ball in that direction, that went horribly so i had to switch back to totally relying on unity physics
i tried it mate, still the same thing, i am able to weird to go up and down in speeds, except that i dont go below the min speed and do go beyond the max speed, so at least thats good
transform.translate totally won't work here
if you remove 2d materials it would use the default one btw
anyway if you have something with a rigidbody you should never mvoe it via transform
ah i see.
i could think of nothing else, so i tried that as well but yea it went how it should have, total fail
yeah, I would ve get the angle and then just redirect the velocity
im sorry english is not my first language. do you want me to do this or ?
could it be the way i am detecting collisions? cause it only happens when i am moving my hitpad fast or something, but then i even tried raycast and same thing still
it would maybe be simpler for you to keep going with physics
I don't want to force you to redo stuff
But honestly... yeah I think you should do that
Right, if you move it it might get odd, I guess it doesn't have a rigidbody on it?
both of them have rb2d, my hitpad and the ball
If the ball is getting too fast that might be because it just hits the pad several times?
But the decrease in speed is kinda odd
yea it gets quite fast, still playable tho haha, but could the decrease be becuse the ball hits the HitPad while both of them are moving and somehow they overlap or something, like i am bad with physics so im not sure but what do u think
try to put on everything friction 0 bounciness 1 material
i just checked, i am indeed using phy mat 2d with 0 friction and 1 bounciness. its applied to the HitPad, do you want me to put it on the ball as well?
also on Ball i have set the collision detections to be COntinious
yeah, I don't recall the default interpolation between those, might help
might do that for pad, it's not stationary afterall
(not sure if it would actually help tho)
just tried it, still able to decrease/increase the ball speed in weird way
heyo im trying to create a script to check for enemies within a room, not how many just if there are any. at the moment i was trying to use OnTriggerStay and Tags to see if any enemy is within the trigger collider. if anyone has a better idea please suggest as this doesnt seem to work.
Itโs probably getting lots of extra collisions due to the curvature of the hitpad
that's true but how it could decrease the speed
actually the hitpad's rb is set to static because if i make it dynamic, the ball sends it flying
i made it that way to have better control over the ball's direction
You need rigidbodys attached for on collision to work
is there no workaround for this?
I said abotu detection mode, not the type
and the type should be kinematic I guess
There is definitely a workaround
but that would break your code
sorry i should clarify, how i have it now its meant to only turn off the door when no enemies are detected, however its detecting the enemies and turning the door off. they do have rigidbodies
oh yea i just did that and still the same thing
and what would that be
How about you have a trigger around the hitpad and whilst the ball is within that and it has collided once already, you make future hits not add to the speed of the ball
you can set the ball velocity to the velocity you desire every frame just in case
that sounds like it could actually work
i tried doing that and it just doesnt work, while doing that i managed to clamp the min and max speed at least
what exactly did not work
U should share the code really
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
im not even sure, i even had debugs and debugs were showing but the velocity was not being set to the one i wanted to.
ballRigidbody.velocity = ballRigidbody.velocity.normalized * Mathf.Clamp(currentSpeed, lastKnownSpeed, nextBallSpeed);
that kinda should be working if you just set the velocity
I mean without clamping
public GameObject Door;
private bool enemiesPresent = true;
private void OnTriggerStay(Collider other)
{
if (gameObject.CompareTag("Enemy"))
{
enemiesPresent = true;
Debug.Log("EnemyPresent");
}
else
{
enemiesPresent = false;
Debug.Log("EnemyNotPresent");
}
if (enemiesPresent == false)
{
// Animation or Effect called Here
Invoke("KillDoor",3);
}
}
void KillDoor()
{
Door.SetActive(false);
}
wait im so so sorry i could be wrong, but am i not setting the velocity here?
using one of the code websites makes it a little easier to read but its okay
ummm guys
oh sorry
you are setting the velocity there
so you may
- have variable curSpeed for current speed
- crudly set the speed each update like ballRigidbody.velocity = ballRigidbody.velocity.normalized * curSpeed
- increase that curSpeed each time you hit the pad curSpeed *= (1 + something)
this looks fine to me do you have rigidbodys on this door object and the enemies
the enemies have rigidbodies but the door doesnt, but the door is still dissapearing just not when the enemies are gone
you might use Physics.OverlapBox / Physics2D.OverlapBox
figured, so you want me to clamp the velocity to the current speed, increase the current speed value from somehwere else, now its clamped to this new value, did i get it right?
ill try that
yeah
i diddnt know about that
yeah those are not needing rigid bodies
but they are tied to physics
I mean colliders update their positions only in physics so if something is somewhere in the update loop but not there for physics system they would get detected likely
but that's a super edge case
should i have this on
private void FixedUpdate , instead of OnTriggerStay?
for when to check?
actually I am not totally sure, maybe rigidbodies on continious detection bypasses those
not ontrigger stay
it would work from anywhere, update or fixedupdate, but I won't recommend to use it every frame, I thought you wanted to do a one time check
i want to check if any enemies are in the room until theres none, like once the player kills all of the enemies the door opens
oh, well, in this case yeah I guess you want OnTriggerStay, sorry
from performance perspective, I think it's better
i believe it should be if (other.gameObject
include the other
but wont it then detect ALL rigidbodies?
I can see why it's not working well, it runs this OnTriggerStay for each collider, so if it ever collides with something which is not an enemy it opens the door
OH
no because you are still specifying the enemy
i was being lazy ill type it out in full
if (other.gameObject.CompareTag("Enemy"))
this door collider encompasses the whole room right
that still doesn't fix what I said tho
so basically
I can only think of one solution rn aside of doing that Physics.OverlapBox / Physics2D.OverlapBox
if (other.gameObject.CompareTag("Enemy"))
{
enemiesPresent = true;
Debug.Log("EnemyPresent");
}
replace that with
if (other.gameObject.CompareTag("Enemy"))
{
enemyTimer = 1;
Debug.Log("EnemyPresent");
}
and in fixedupdate substract from that timer Time.deltaTime
and if it's zero you open the door
because in your current realization it just cycles through things inside the trigger collider
and if one of them is not an Enemy it opens the door
your script can be simplified to
if (other.gameObject.CompareTag("Enemy"))
{
enemiesPresent = true;
Debug.Log("EnemyPresent");
}
else
{
// Animation or Effect called Here
Invoke("KillDoor",3);
}
that still won't fix what I said
yes
okay
so im kinda stupid and just checked the console, it is only detecting the enemies once
you should listen to what the other guy is saying really
ok
can you expain what this does cause i dont get it
is it basically adding a time buffer every time the enemy is detected?
oh it sets to 1 until it no longer detects them
I would rather set bool to false at the beginning of the loop and set it true if any of enemies is detected, but FixedUpdate runs before OnTriggerStay
ok quick question if an object is already within a trigger will OnTriggerEnter work?
and OnTriggerStay is not a loop, it runs each time for each object
shouldn't? it's only about entering
dang
at the scen start it will trigger one Enter I think
double checking is always worthwhile tho
then what im hoping is that on death it Triggers OnTriggerExit
Deactivating or destroying a Collider while it is inside a trigger volume will not register an on exit event.
so, no
do the doors close seemingly randomly
open then
it doesnt look random
what causes it
it still happens because of the Invoke
okay
a more professional way to do this, would be to note how many enemies are in this room one time when the player enters it
using physics.overlapbox and an int
and then reduce the int by one per enemy killed
once the int is 0, open the doors
little room for errors there
i just tried doing the exact same thing but with OnTriggerEnter and Exit
which didnt work
so ill try that now
how can I check once a unity scene has finished loading? I'm using a framework which is meant to have a. callback for this but it's firing early. is there a unity event for when the scene is all done loading?
changed my mind
this is what im trying to do but im not sure how to check for specific Boxes https://hatebin.com/sjpqgyefkc
See if this helps
Collider[] hitColliders = Physics.OverlapBox(transform.position, transform.localScale / 2, Quaternion.identity);
foreach (Collider hitCollider in hitColliders)
{
if (hitCollider.CompareTag("YourTag"))
{
int++;
}
}
but how am i subtracting that number when they die?
in whatever code you have for them dying
i can see how it might cause problems outside of this one time, like if i killed enemies outside this zone in a previous room it might subtract that from the int
im resetting my sleep schedule so im probably too poop brained to help
all good
thanks for the help you did give
cause im sure im getting closer to solving this
know that if youre tired the best thing you can do is sleep then come back to it when you wake up
always works for me
lol fuck
yeah
yo start your homework earlier man
this was on the backlog
and isnt the last item
other people in a group project not holding up thier weight and stuff
and its left to me
the enemies that spawn in each room would use their own instance of the script, more complicated than i anticipated really
System.RuntimeType.InvokeMember (System.String name, System.Reflection.BindingFlags bindingFlags, System.Reflection.Binder binder, System.Object target, System.Object[] providedArgs, System.Reflection.ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, System.String[] namedParams) (at <b11ba2a8fbf24f219f7cc98532a11304>:0)
private void OnEnable()
{
shoot = controller.Player.Shoot;
controller.Player.Shoot.performed += OnShoot;
shoot.Enable();
}
private void OnDisable()
{
controller.Player.Shoot.performed -= OnShoot;
shoot.Disable();
}
private void OnShoot(InputAction.CallbackContext context)
{
Vector2 spawnPosition = spawnPoint != null ? spawnPoint.position : Vector2.zero;
Instantiate(boomerang, spawnPosition, Quaternion.identity);
}```
jello, i cant quite seem to see the problem here, but does anyone know?
i know that story
it's marked as private
ive tried changing it to public, it still wont work
then there must be an incompatibility between what is looking for the method and the method signature you have defined
the script actually works, but it just gave that error somehow
Lol I know this feeling
im not even a programmer im only a designer
i just have the need to know some programming
screw it im desperate
For things like this I'd inform your teacher on how bad your group communicates
But I assume that they don't care
as in OnShoot runs after it says it's not found?
oh i have, and the teacher has taken notes
i think game students are half wanting to make games and half thought thought they would be playing games all day
yea so basically the error comes up after the script works (spawns object when i left click), magically
probably something set up wrongly in your input actions
so far out of my cohort its more 10% thought it was just playing them, 30% dont see it as only a means to get money and dont care for anything past that and the other 60% either give plenty shits or are genuinely passionate, which i see as a decent margin
you should focus on the project lol
yeah
how to fix this (Can't add script behaviour 'NpcInteractable'. The script needs to derive from MonoBehaviour!)
dont think theres such a thing as NpcInteractable
Make sure your script derives from MonoBehaviour and that you don't have any compile errors
I do all this and ever time give me this error
You did something wrong
You should start sharing your code and/or screenshots of your Unity Editor and console window.
Right now we can't see your project so we can't tell what's wrong
its simple codes look
ok so i fixed it by changing the name to OnClick, does anybody know why that happens??
programming is weird ffs
Looks like you have some compile errors
you need to fix all compile errors, like i already said
It doesn't matter how simple the code is, it has errors.
If you're talking about the PlayerInput component in SendMessages mode, the parameters need to be InputValue not CallbackContext
it tell me the error is ChatBubble3D it not exits in the current context
Yep, you have to fix that error.
You're trying to use a type that doesn't exist or you are missing a using directive
ok....................
So, either add the missing using directive
Or make sure you're only using things that actually exist
ChatBubble3D is probably an asset? Which will be in its own namespace, so you'll need the correct using ... at the top to be able to access the ChatBubble3D type.
i will try
RIght I said that....
add the missing using directive
If you hover over the erroring code in Visual Studio it will automatically suggest this fix
if that is indeed the problem
hello can someone help me I want to make animations for moves for my pokemon game pls explain how to do it with dotween
Are you just asking "how do I use DOTween" in general?
No like I made some transitions like fainting and all but have no idea how to make all the Pokemon moves with dotween
That's extremely vague
I actually tried to do it with animations but navarone said that due to transitions with dotween it would not work
MP4 to embed in discord.
ok but look I have the ChatBubble3D and it give me the same error
Show us
That's a prefab
That's not a class or script
You cannot reference classes that don't exist in code.
what i do
Where are you even getting this ChatBubble3D stuff from?
You clearly didn't write it yourself
i creat one and it didn't work for this i get one from unity assest store it npc dialouge
Follow the basic rules of C# programming
What?
yes I am stubbed
plz help me i don't know what to do
Learn the basics of coding would be the first step
As for the specifics of this particular problem, you're not providing enough information for us to help you
Hello I'm new-ish to coding/game design I'd say I'm maybe a moderate beginner or expert beginner. Anyway I'm trying to code my first game ever using Unity and right now I have just movement and camera following. It's going to be a 2d platformer. I'm having a couple of issues one I can jump infinitely in the air instead of just a double jump. Two I have no idea wtf I'm doing. Should I be following tutorials to the tea should I code it on my own do I use some tutorials and do other things on my own. Plus I have no idea how to start coding things on my own like I understand coding but how do I start with a new mechanic. Anyway that's just me. If anyone has idea's or tips I'm open to them.
Also let me know what information you need to help like code screenshots, files, etc.
focus on one issue at a time. Yes, you should share your code and explain how your jumping works if you want help with the jumping thing
I have no idea how to start coding things on my own like I understand coding but how do I start with a new mechanic
This usually comes from unfamiliarity with the Unity API and the basics of how to do things in general and will go away in time as you become more familiar with it.
if (jumpCount < 2)
{
...
jumpCount++;
}```
first of all you should learn coding instead letting ai do the work for you
This was not ai it was a tutorial
sure
I can literally send you the video for it
in future send code as code block please.
Show your Support & Get Exclusive Benefits on Patreon (Including Access to this tutorial Source Files + Code AND the State Machine version for this project) - https://www.patreon.com/sasquatchbgames
Join our Discord Community! - https://discord.com/invite/aHjTSBz3jH
--
Getting a jump to "feel good" is one of the most important things to get rig...
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
debug.log your isGrounded see if it is working correctly when you are on the ground
that might be the reason why you can jump in the air too
How excatly do I Debug.log cause it doesn't let me in the code. has an error
Whenever you get an error you're not sure about you really need to share the exact code you tried and the exact text of the error you get.
Otherwise there is no way to help you. "An error" is about as vague as it gets.
{
controller = new PlayerController();
Vector2 mouseCoords = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Debug.Log(mouseCoords);
}
private void OnEnable()
{
shoot = controller.Player.Shoot;
shoot.performed += OnClick;
shoot.Enable();
}
private void OnDisable()
{
shoot.performed -= OnClick;
shoot.Disable();
}
public void OnClick(InputAction.CallbackContext context)
{
Instantiate(boomerang, mouseCoords, Quaternion.identity);
Debug.Log(mouseCoords);
}```
every time Awake() happens, debuglog mouseCoords returns the actual coords. but when debugLog mouseCoords on OnClick happens, it returns 0, 0, and the script does so. does anyone know why?
Debug.Log($"{isGrounded} {isJumping}");
You have two different variables named mouseCoords
you also need to make sure to update the value of the variable because just assigning it once in Awake will not make it constantly update to the current coordinates
It gives this error 'Debug' is an ambiguous reference between 'UnityEngine.Debug' and 'System.Diagnostics.Debug'
yea i just realized it after i tried it xd
remove using System.Diagnostics; from your code
yeah it simply means Debug exists inside of both of the namespaces
The debug says they are both false for ever doesn't change
well there you have it, make sure to fix these 2 bools
the ground detection seems faulty
why is my text so low res?
probably because its not textmeshpro
idek what that means
thx
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
The daynightcycle didnt work :/
Im using default unity skybox by the way, the skybox lights are going independently and didnt match with the terrain lights
how can I make the player able to move sideways while colliding in front? (Like pressing W, colliding, but if you press A or D you can move to the left/right)
{
moveDirection = orientation.forward * verticalInput + orientation.right * horizontalInput;
Vector3 moveForce = moveDirection.normalized * moveSpeed;
rb.AddForce(new Vector3(moveForce.x, 0, moveForce.z), ForceMode.VelocityChange);
}```
I'm trying to do my initial commit, but I get a bunch of errors warning me that the line endings will be changed from 'LF' to 'CRLF' and the commit doesn't go through. Can anybody help with this?
For starters, you're not using the Unity gitignore: https://github.com/github/gitignore/blob/main/Unity.gitignore
As seen by the fact it's trying to commit the Library folder, which you do not want added to your repo.
I did select Unity from the drop down list when I created the Repo, but maybe it didn't take for some reason. Do I need to start a new repo to fix that or is there an internal setting?
You can fix it if you want to get fancy with git, but it's honestly easier just to start a new repo.
Make sure you commit it first before adding your project files.
ok
Take the gitignore from the link above as well, and commit it as its own file.
@past spindle for the record, looks like your project isnโt in the root of the git repo. Make sure that either the project itself (contents of the folder that has Assets and ProjectSettings folders) is at the root of the repo, or the .gitignore file is placed in the project folder next to Assets and ProjectSettings.
I see what you're saying. When I create a new project in the repo file, it creates a new folder. Would it be better to move the .gitignore file into the new folder or to move the project files out of the new folder?
or does it matter?
Either works. If the repo just contains a Unity project, Iโd personally move the project
I wasn't sure if it would mess with the path the hub needs to open the project
The key is the gitignore needs to be next to the project files
And yeah, youโd need to add the new project location to Unity Hub. Takes 5 seconds, though
guys how can i make this spawning animation without scaling?
masking
Whats that? Ill read into it, thank you!
what is the proper way to get a world position, and translate it to a canvas postion, when the canvas is using Screen Space - Camera mode?
i was using transform.position = Camera.main.WorldToScreenPoint(worldPosition.position); however, after moving over to not overlay, it causes it to be super off.
ah, so id go from world point to screen point to point in rect?
hmm, yeah still not working. ends up giving me a value thats 67000, -23000, -67000.
exact code is.
void FixedUpdate() {
if (worldPosition) {
lastKnownPos = worldPosition.position;
}
Vector3 screenPoint = Camera.main.WorldToScreenPoint(lastKnownPos);
RectTransformUtility.ScreenPointToLocalPointInRectangle(transform.parent.GetComponent<RectTransform>(), screenPoint, Camera.main, out Vector2 localPoint);
transform.position = localPoint;
transform.rotation = Quaternion.Euler(0, 0, 0);
}
ah setting it to transform.localposition fixed it, strange, but I suppose.
Yeah the method outputs a position relative to the parent rect
Not strange, the name Local is in the name
why can i not see my text?
It's not on a canvas
how do i put in on a canvas?
you mean something like that?
Yes, now move it into position on the canvas
In this screenshot you can see the bottom-left corner of the Canvas, it's the two white lines extending up and right off of the screen.
The canvas is huge compared to your world, and it's normal (1px = 1 meter). You can click the Canvas in the Hierarchy, and while having your mouse over the scene view, press F to bring it into view
ahhh ok
thenks
does smoothdamp need time.deltaTime?
to stay framerate consistent? or is that done within the function
did you look at the docs?
can't say i have
Hello there, i have an issue with raycasts in 3D... I am making a little game about a cube. There are teleporters in my game, and i have a raycast for the ground check going from my cube to vector3.Down. When i teleport, the raycasts stops detecting any collision.. Could some1 help, i can call if needed because it's really a strange problem...
here is my cube code : https://pastebin.com/xET7auwT
and the tickManager : https://pastebin.com/JSa3QQkJ
thank you for your help
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
docs should always be the first place you check before asking here. your question would have been answered immediately
- if you're going to use pastebin, at least have the courtesy of selecting the language so that there's syntax highlighting so the code is easier to read/navigate
- you never invoke your _NextAction delegate which is where you call CheckCollision except for in that CheckCollision method. are you certain that logic for counting the ticks and invoking the delegate shouldn't be inside Update instead? or even DoActionVoid?
oh i suppose it's also subscribed to your OnTick event as well. but have you actually done any debugging to find out when/if these methods are actually being called as you expect?
sorry i didn't knew thtat i could select the language
can you actually be specific instead of expecting people to read your mind? did you even check #854851968446365696 for what to include when asking for help?
yes, how could i detail more.. I will try, i have the blue cubes that are the teleporters. When my cube teleports to the top, like on the second screen, the raycast fires but, nothing happens. He stays blocked. when i tried debbuging, after the teleportation, the raycast doesn't detect the groundTag gameobject. I suppose its because the ray hits the teleporter before it hits the ground. but i have no idea on how to fix it.
here is the cube with the good language : https://pastebin.com/qHSZfVGu
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
you said you've been debugging this for 3 days, what useful information have you found from your debugging efforts? what have you actually done and what did that reveal?
the only good info i got was that after teleporting the condition if (_GroundHit.collider.CompareTag(_GroundTag)) at the line 90 in checkcollision doesn't execute. But i think its not relevent after thinking about it because i just use the setmodewait so we dont care about the checkCollision because i invoke the action int the setmodewait
i am new to c# so i am missing something for sure but i dont get what
is this specific enough ?
so you've spent 3 days debugging and the only conclusion you've come to is that the code is not executing?
also this statement "i just use the setmodewait so we dont care about the checkCollision because i invoke the action int the setmodewait" is incorrect because SetModeWait does not invoke the action, it is CheckCollision that is invoking the action, in fact SetModeWait is just assigning the lambda expression that calls CheckCollision to the action that is being invoked in CheckCollision. if CheckCollision is not being called at all anymore, then obviously that action will never be invoked. have you confirmed that this code is actually executing
it does execute
now verify that the raycast code is actually executing
it does execute but stops at the if (_GroundHit.collider.CompareTag(_GroundTag))