#💻┃code-beginner
1 messages · Page 630 of 1
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
can someone help me double check my scripts like why isnt the heatlh bar going down when the enemy takes hitpoint damage? floating health bar script : https://paste.mod.gg/cttrxfkqffzg/0
A tool for sharing your source code with the world!
health script: https://paste.mod.gg/yisfthmlesbp/0
A tool for sharing your source code with the world!
sprinkle some logs in there to make sure the methods are being called as you expect them to be
hmm ok
how do i collapse that console it keeps spamming random messages that i dont want?
does anyone know how?
ok i got some logs now!
okay so have you confirmed that the methods are being called as you expect?
show the code with the logs so i can see what you actually logged. and also show the logs in the console
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
you know you can bookmark those links in your browser so you don't need to use that command every single time you want to share code
floatinghealthbar script https://paste.mod.gg/uhukrxmzjagp/0
A tool for sharing your source code with the world!
Enemy health script https://paste.mod.gg/dkrnphqqhekh/0
A tool for sharing your source code with the world!
console
okay so it does appear to be modifying the fillAmount correctly. are you sure nothing else is affecting it? or that you are looking at the correct instance?
nothing else is affecting it
need help on this, player doesn't jump when i hit spacebar but movement right and left work fine. Thanks
without the code what exactly are we supposed to do with this image?
can someone tell me why my healthbar isnt updating?
floatinghealthbar script https://paste.mod.gg/uhukrxmzjagp/0
A tool for sharing your source code with the world!
Enemy health script https://paste.mod.gg/dkrnphqqhekh/0
A tool for sharing your source code with the world!
console
where is this Debug.Log("Updating health bar...");
i dont see it logged anywhere in console
it's in there
19:39:04
oh wops im blind
not even an Animator?
in play mode?
yea like the healthbars
video or pic?
pic should be fine, show the inspectors + components
if you are absolutely certain that nothing else is affecting it and there is no Animator on the object then you are looking at the wrong instance that is being affected.
yep no animator
show the image component for this
{
private float horizontal;
private float speed = 8f;
private float jumpingPower = 16f;
private bool isFacingRight = true;
[SerializeField] private Rigidbody2D rb;
[SerializeField] private Transform groundCheck;
[SerializeField] private LayerMask groundLayer;
void Update()
{
horizontal = Input.GetAxisRaw("Horizontal");
if (Input.GetButtonDown("Jump") && IsGrounded())
{
rb.velocity = new Vector2(rb.velocity.x, jumpingPower);
}
if (Input.GetButtonUp("Jump") && rb.velocity.y > 0f)
{
rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.5f);
}
Flip();
}
private void FixedUpdate()
{
rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
}
private bool IsGrounded()
{
return Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
}
private void Flip()
{
if (isFacingRight && horizontal < 0f || !isFacingRight && horizontal > 0f)
{
isFacingRight = !isFacingRight;
Vector3 localScale = transform.localScale;
localScale.x *= -1f;
transform.localScale = localScale;
}
}
}
put it in !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
the image component
Put log inside the jump method and see if its called
this is not a filled image
no wonder it wasnt working 😛
what does that mean
it happens
how would i fix this glitch where instead of going from down to up it would go side to side?
oh wait nvm i found the method
Hi I have a unity project for my coursework which is a toothbrushing game. I have it so that a polishing type sprite appears when a tooth is clicked on, and then it disappears a second later. I have done this by using the OnMouseDown function for enabling the sprite and then a seperate function called Hide for disabling which is called from within OnMouseDown. All works well but I have a problem. If there are too many successive clicks, the sprite only appears for a fraction of a second, as if the coroutine isn't working properly, almost like jump fatigue 😂, does anyone have a fix for this?
Here are my functions
private void OnMouseDown() {
mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePosition.z = 5f;
sprite.transform.position = mousePosition;
sprite.enabled = true;
StartCoroutine(Hide()); }
private IEnumerator Hide() {
yield return new WaitForSeconds(1);
sprite.enabled = false; }
You're running multiple coroutines, you need to store the coroutine which is returned from the Start coroutine function. Then you can stop the one that's running so you can start the new coroutine
Pretty much exactly how I described. Use the return value from the start coroutine method and store that in a coroutine variable.
So I declare my data type as Coroutine?
I understand so I do private Coroutine answer = StartCoroutine(Hide());
But where do I call the StopCoroutine function?
In the OnMouseDown function?
you can't start the coroutine in the field initializer, you would just assign to that answer field where you normally start the coroutine
Look at one example in the docs above, you dont call start coroutine outside of a method.
but yes you would call stop coroutine in OnMouseDown, check if the coroutine is null and if it isnt, call stopcoroutine on it. At the end of hide() you can set the coroutine to null.
So coroutine starts, answer gets the return value from start coroutine, then answer is set to null when the coroutine finishes
Literally the word null?
Yep it's a keyword, you can set the coroutine to null. In this case itd mean there is no currently running coroutine
Hey i have a hopefully simple question/problem. Ive made a very simple game for android - it built and installed etc fine, however whenever i try to tap on the objects to break them, the event doesnt work. I'm using OnMouseDown() since I was under the assumption that would handle Tap input on gameobjects however it doesnt seem to work.
(Im new to unity, moving from UE5)
How do i make it so it registers me tapping on a gameobject with a collider2d on it ?
are you using the new input system...? i beleive OnMouseDown isnt working with it... instead you should implement the "IPointerDownHandler" interface and use OnPointerDown() ...
yeah im using the new input system. I'll give that a go
didnt work. thanks though.
It will work there's just a few steps to set it up properly
You need to make sure there's an event system in the scene and a Physics Raycaster on the camera.
The code needs to be correct as well
I didn’t even think of the physics raycaster xD unity is more complicated than unreal. Unreal it’s just a node in blueprints plug and play haha
Both engines are very large complex beasts, I wouldn't make a judgement based on one small factor
No I get it. I was using UE for almost 10 years and completely forget out much I struggled learning that so it’s frustrating learning something in a new workflow when you can do it easy in another Yknow? Same from 3ds max to blender :p
Do anyone know how to get current sprite of rule tile in code. I can't find it in web. In the script i have that variables:
public Tilemap tilemap;
public Sprite targetSprite;
I found
Anyone knows how to fix this? I am new to unity and coding, I made a project and I am following a tutorial, it said create a c# code in a folder, but when I look the only thing of code that pops up is monobehaviour and no C#, anyone knows the reason / how to fix it?
You can use that. The only difference is the default contents of the file
and don't cross-post
Anyone got tips or resources on why sprites may jitter and be super buggy in unity2d when moving fast, even when enabling interpolation to the rb and using fixedupdate
Could you tell me what cross-post means?
Posting the same message to multiple channels
@wintry quarry @gentle bone thanks so much for you help guys! got it working finally. ive spent the last 2 days googling and everything XD
Hi, I don't understand why my normal map behaves this way
it's transparent technically
it adds this weird background
This is a coding channel, #🔎┃find-a-channel
ah I see
yoo guyss, as I finished unity essentials pathway and started the Junior Programmer halfway, I can say that I am finally Learningg!!!🤩
I literally came from a tutorial trap to believing that Flappy bird is actually so easy to make now... Unity learn really does the job.
Do I understand correctly that unlike UE5, Unity Overlap spheres/boxes are only at code level and are not visible on the level? Is there maybe any add-on that adds this functionality to Unity?
I think you'll be able to see that using the Physics Debugger, it can be accessed in Window -> Analysis -> Physis Debugger
otherwise it's always possible to use Debug.Draw ou gizmos
Hi guys, C# question here-
When exactly does array indexing pass an element by value, and when exactly is it a reference?
I know that there're tricks that allow you to seemingly bypass the pass by value issue that struct in arrays has
For example, writing a function where you pass a value in with the ref keyword, that one allows you to modify array elements directly within the function
Your question isn't tied to arrays afaik
value types aren't passed by reference unless they are explicitly used with the ref keyword
otherwise they are just values
Well, why I'm asking about arrays specifically is since setting a value in a struct in a struct for example isn't a problem...
structs can hold reference types, but the struct itself is a value
I'm having kind of an abstraction issue where I don't want to permit direct access to the map, so I added a function to get a chunk- But then the problem is that I have no idea how to pass a chunk out as a reference
Like, the cleaner looking the better
There're some ways but I'd really prefer not to use those
Ah, nvm, I think I found what I was looking for- Seems like I was never aware that return value may also use the ref keyword
My bad '^^
Been searching a while but the fact to search "c# return struct by reference" never actually cross my mind
Holy crap somebody actually learning. May your unity career be vast and fulfilling
So I have implemented this as it seems like the best choice for what I am doing, but I cannot access the struct list the spawn tables inherit in the inspector. Here is what it looks like now compared to before:
Here is the scriptable object with the list that is being inherited ```public struct SpawnChance<T>
{
public T type;
public int chance;
}
public class SpawnTable<T> : ScriptableObject
{
public List<SpawnChance<T>> spawnChances;
}```
and here is the scriptable object in questions [CreateAssetMenu(fileName = "RoomSpawnTable", menuName = "Scriptable Objects/RoomSpawnTable")] public class RoomSpawnTable : SpawnTable<RoomType> { }
Any idea how do i improve collision here?
What i exactly want to do is to make the collision smoother and to disallow the player from moving through the spinner
thx!! I appreciate your help i'll try it now
you can use ref or out
void WithRef(ref int val)=> val++;
void WithOut(int[] arr, out int val)=> val = arr[1];
int[] arr = new int[]{1,2,3,4};
WithRef(ref arr[1]);
WithOut(arr, out var testOut);
and yes, out will always return by ref if anybody confused
I'd just pass their indexes if I were you, refs and outs will add extra indirection... not a big deal ofcourse
Umm... Return by reference but... Out means write to (whatever place you designated), right?
But when you stored it, it won't be a reference anymore pretty sure?
yeah
if that's what you want just pass their indexes
dont use ref or out at all
Ye... Except it would show the (kind of unintuitive) innerworking...
wdym?
Since the map are chunks but then splitted into tiles
So if you wanna access a tile, you would actually have to access a chunk at index position divided by chunk size, and then access the tile inside it
that's not true? proly just a matter of personal preference I'd say... you can ofcourse wrap them in a method etc
You consider it intuitive of concept?
I mean, why not? we're not Picasso, we don't make things look pretty
Consistency and readability is typically highly recommended, though...
do you think accessing them via indexer to be unreadable?
again it's a matter of preference
Maybe
It's just pretty inconsistent with how to access tiles
Though honestly what makes sense depends on how you think about things
Unfortunately it did not work : /
Do I need to make a custom script for it? or do i need to keep changing few things in the settings?
if that didnt work it makes me think the code u have moving the thing isn't a Rigidbody function
if u use translations physics aren't respected
there's a way, but again you can't store it in a collection, as local refs it can... AND it's very unsafe
int[] arr = new int[]{1,2,3,4};
ref var tref = ref MemoryMarshal.GetReference(arr.AsSpan());
Console.WriteLine(Unsafe.Add(ref tref, 2));
I'd prefer my original solution than that tbfh
so if any of ur code is transform. = blabla <-- thats teleporting the object directly..
Oh nono I don't really need to do that
I'm not really sure wdym by that as i'm still a beginner in unity, but as far as i know i'm moving the spinner through rigidbody
Just a sec i'll share my code with you
shit i forgot this is code beginner
goes for the tank too..
I mean, it's either pass back by reference, or indexing...
just use indexers and call it a day imo
Hmmm... Hey, could I have your opinion on something
anyone has an idea why in my gameover screen there is no mouse to see, so you cant click on anything
i have many small problems with my game hahga
but idk how to fix them
I suggest you simply unlock the cursor whenever the game's paused or something...
Depends on how you expect it to work...
in the main menu its working
this is the code of the spinner:
public class Spinner : MonoBehaviour
{ [SerializeField] float xAngle = 0f;
[SerializeField] float yAngle = 0f;
[SerializeField] float zAngle = 0f;
Rigidbody myRigidbody;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
myRigidbody = GetComponent<Rigidbody>();
}
// Update is called once per frame
void FixedUpdate()
{
Quaternion currentRotation = myRigidbody.rotation;
Quaternion deltaRotation = Quaternion.Euler(
xAngle * Time.fixedDeltaTime,
yAngle * Time.fixedDeltaTime,
zAngle * Time.fixedDeltaTime
);
Quaternion newRotation = currentRotation * deltaRotation;
myRigidbody.MoveRotation(newRotation);
}
}
And this is the code i'm using for the tank:
using UnityEngine.InputSystem.Interactions;
public class Mover : MonoBehaviour
{
[SerializeField] float moveSpeed = 7f;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
PrintInstruction();
}
// Update is called once per frame
void Update()
{
MovePlayer();
}
void PrintInstruction()
{
Debug.Log("Welcome To The Game!");
Debug.Log("Move using key arrows");
}
void MovePlayer()
{
float xValue = Input.GetAxis("Horizontal") * Time.deltaTime * moveSpeed;
float yValue = 0f;
float zValue = Input.GetAxis("Vertical") * Time.deltaTime * moveSpeed;
transform.Translate(xValue, yValue, zValue);
}
}
So, you have the mouse in main menu, then you go into game which is in FPS mode, and then you go to another scene, correct?
see how ur spinner is using a rigidbody function.. thats fine..
right when oyu die it is switching scenes
but ur player move script is using translation
OHHHH
transform.Translate.. <-- that wont respect physics
Check out the Course: https://bit.ly/2S5vG8u
Discover 5 different ways to move your Unity3D gameobjects, see some of the differences between them, and learn which one I usually use.
More Info: https://unity3d.college
that's what's causing the error
heres a good video that explains the different types of movement
Thanks man!!! I really appreciate that
Yeah simply write a script that would unlock the cursor on start if you'd like
Now i know what to fix!
ty
I'm quite certain it's simply that the cursor's lock state doesn't reset upon switching scenes
probebly
i've been working on a system thats a CursorManager..
a singleton.. <-- its wat keeps track of cursor
and if anything wants to lock or unlock it it needs to go thru that script
Yea but... I don't think they wanna go through the hassle of making a whole system lol
(1) place modifying it.. soo only (1) place things could go wrong..
true.. its the premise more than anything..
I made my own cursor manager too, and stacking input manager and what not, so yea... It's not that I don't know how to do things properly, it's just that it feels wrong to suggest such a route for a beginner
i just had a long conversation the other day.. where this guy was manipulating the cursor state.. in his player controller..
in his pause menu.. and a few other places..
just asking for a bad time
And that, is how devs make games out of ducktape and coffee lol
and u dont need an entirely new system..
just a Manager type script.. that his other code could call..
instead of handling the cursor lock state on its own..
and since its a singleton.. it carries over to all scenes..
ezpz 🍋 squeezy
TLDR: control ur cursor from (1) singular place..
Yooo is there a way to set the "raycastTarget" with a script? if so how can I do that?
referenceToSaidScript.raycastTarget = theThingYouWantSet;
Choose the best way to reference other variables.
uhhh so my script is called "ChanceScene" and my variable is called "black" so do I put "ChangeScene.raycastTarget = black;"?
I want to call it in the "ChangeScene" script
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
public class SceneChanger : MonoBehaviour
{
public void LoadScene3()
{
SceneManager.LoadScene(3);
StartCoroutine(UnlockCursorAfterDelay());
}
private IEnumerator UnlockCursorAfterDelay()
{
yield return new WaitForSeconds(0.1f);
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
}
With these script i still have no courser
maybe its an other problem?
👇
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
Add a Debug.Log after the yield return, if it doesn't print, it means that you either didn't execute function, or the object the IEnumerator's on has been destroyed
it didn't work btw 😭
I'm pretty sure that Coroutines are stopped when the Object has been destroyed
does anyone know how to do it?? 😭
the link i sent describes all the ways to get references to other scripts..
the easiest which is [SerializeField] MyScript referenceOfScript;
then u can just assign it in the inspector.. (also have to make sure any variable or method you're wanting to access outside that class is public)
it dosent print anything
configure your IDE
The type in the list needs to be marked Serializable
u could use an Image variable and not need to use the extra GetComponent if u wanted to
like: black = Image;?
using UnityEngine;
using UnityEngine.UI;
public class T322 : MonoBehaviour
{
[SerializeField] Image myImage;
}
Could you give me a reference for further reading on how to do this?
ohhhh It worked!
ofc it did lol
I tried to do that before but it didn't work
thanks anyways
I already have that too
yeah
same concept can be applied to pretty much every type
if ur only using the gameobject to grab some other component.. u can use it instead..
and its easier to work backwards.
can get the gameobject off of the component instead
So the list needs to be serializable or the struct itself? Sorry this is way beyond my knowledge
can someone help me why ma animation isent playing on my mosnter charakter?
idk how to mark it as "legacy"
The type in the list
So that would be the struct
Okay perfect, I think I have it working: ```[Serializable]
public struct SpawnChance<T>
{
public T type;
public int chance;
}
public class SpawnTable<T> : ScriptableObject
{
public List<SpawnChance<T>> spawnChances;
}``` I've learned so much, thanks!
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Can you paste what the IDE is saying? i.e the error when you hover over the red line
anyone know a good resource for developing photon fusion hostclient firstperson character controller?
this is where i have defined everything
ignore my last message - i assumed angular velocity was always a vector. Im going to look at some docs 🙂
it seems 2D angular velocity is always a float - https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Rigidbody2D-angularVelocity.html >>> A Rigidbody2D can only rotate around one axis (the Z axis) so the angular velocity is a single float value rather than a vector.
so your angular velocity.x and angularVelocity.y wont exist at all and the vector assign wont make any sense. You have to assign a float not a vector
Can someone help with my code? Its not working and im not sure why. Its mainly the sprinting feature. Also am i supposed to paste the whole script? (Its 154 lines long) or do i just take screen shots of the main part?
theres more code its just that its not related to the sprinting part
i think they recommnend using pastebin for large code blocks. But idk what the best practice is for situations like this - im very new here
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
oh your also a beginner?
please don't use screenshots to show code
new at unity - not so new at c# 🙂
My bad
see the ! code embed above
thanks, but for the scriptbin one do i share the URL?
it looks like you can paste a script and click save - the url will be updated and you can paste that - https://scriptbin.xyz/cayosegeha.less
"it's not working" doesn't give us much info to work with
what exactly is happening that you don't want to happen?
https://scriptbin.xyz/uceyuhalid.cpp Like i get the first Debug log for the "Started stamina usage" but then it doesnt do any other debug log
Use Scriptbin to share your code with others quickly and easily.
staminaIsRecharging starts as true so the loop in the coroutine is immediately skipped
Ahh thanks
is that the only issue?
That's the immediate reason why no other logs show up, I can't run the entire code in my head
okay thanks
ello what is up
I think I am missing something fundamental here but can anyone shed some light here:
I have created a test folder in unity that lives at Assets/Scripts/Tests and have a bunch of public classes I want to access defined in Assets/Scripts. I'm having trouble getting my test script to reference those classes as they are not defined in the context while I'm running my script. Can someone help explain to me what is going on with the scope and context here when I run tests through Unity TestRunner?
you may need to add your assembly definitions *
Yeah for the test runner you should be using asmdefs for your own code that your test asmdef references
public object[][] weapons = new object[5][];
weapons[0] = new object[] { "Blaster", blasterimage, "A gun shooting homing projectiles", blasterchosen, "bla", (Action)blaster};
how can i add the void method to onclick in my button?karta1.onClick.AddListener((UnityEngine.Events.UnityAction)weapons[x][5]);
ive tried this but it doesnt work any ideas pls
hey so i need some help making a upgrade system for my game so basically im making a mobile game similar to games like idle miner and adventure capatalist and i have stands that every time i click them they take X amount of time and generate X amount of cash but i want to be able to upgrade it so you can make it quicker and generate more cash each time but im not sure of a good way to do this without it getting out of control way to fast
i also plan on adding more areas that let you get more money faster each area will have 6 stands
my current stand script is this https://pastebin.com/evEkkC1T
and currently if you upgrade 1 stand to have like 20 price upgrades 5 cook time upgrades and give it a chef you can get to trillions super fast which i dont want it to be able to do (with max upgrades for the area for all 6 stands and a chef you should be barely getting a million (i havent added a max for the upgrades yet but i would like it to be like a max of 50 for price or smth and like 10 at least for cook 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.
Just found this forum off a quick google. Let me know if this helps at all? https://discussions.unity.com/t/system-action-to-unityengine-events-unityaction/900865
i just found the issue but still thank
in the object it was just action so i had to change it to UnityEngine.Events.UnityAction and it works perfectly
consider using a struct to store each weaon's details
try to avoid excessive casts
i dont know what that is. and can u explain what do u mean by casts
stop using "object", that's bad code
(T)value is a cast
try googling "c# struct"
i dont think it would fit my idea here. i saw i could use classes instead of objects but ive watched videos explaining them and i still understand nothing so i just went with objects will it be really bad?
use dynamic instead
object is the base class for all classes in .NET (c#). While it means you can store anything in the array - it means accessing it gives you anything. It makes maintainability very difficult alongside boxing/unboxing issues all over the place
classes/structs are objects
they just aren't object
object is very broad, it's like saying "an array of something"
using a struct/class gives you names for the members as well
boxing/unboxing is just going from value types (int, char) to reference types (classes , etc) . theres a slight performance overhead for this but i think its the least of issues here. Just wanted to give some context
also gives encapsulation in your code ( all stuff do with a thing goes in one class)
does c# even have boxing
oh damn it does, nvm sorry
i believe its as i said above - gooing from value type to reference types
yeah
I think the issue here is that you want to approach the problem from a place of understanding. Programming takes time to learn and the more time you spent learning about classes and other language features, the more you will be able to help yourself. If you don't understand something, take the time to study and experiment!
i didn't realize it would do that implicitly with object
i was thinking of how that works in java, where there's corresponding value and reference types that can box/unbox
anyone able to help me with this?
you don't have any punctuation, what's your actual question lol
yeah sorry about that. my question is mainly how i can improve what i have so instead of after only a few upgrades being able to make trillions of cash. i want to be able to have all 6 stands be maxed out with like 50 upgrades for price and like at least 10 for time and still barely be able to get a million
idk if the issue is my math or smth
any tutorials you guys recommend about clean code?
scale the upgrade cost
maybe linear, maybe exponential, maybe polynomial
open up desmos and try finding a line/curve that has values that scale well with your economy
issue with that is there is no real way to scale the upgrade cost to fix this because it goes from making nothing to making trillions way to fast
so if i scaled the upgrade cost people would need to spend hours before they could get there first upgrade
havent looked at any of the code - but you could use something like a predefined curve for the upgrades earn rate. you can have points along the x axis represent levels and the y value being earn rate (maybe keep this between 0 and 1). Then just scale max earn rate accordingly?
you can also apply a curve to things like upgrade cost as suggested above
i don't mean "make all your upgrades twice as expensive"
i mean "make subsequent upgrades more expensive"
like if the first upgrade costs 10, the next might cost 20, then 45, then 100, then 230, then 475, etc
yes but after like 5 upgrades your making millions for some reason
if progress scales up, then costs should also scale up
if progress scales too much, either reduce progress, or increase costs
this isn't really a code issue
theres always an idea of a prestige after X amounts of cash 🙂
it's a design issue
you need to figure out how you want your economy to work, how it scales
true
but i think i made a mistake with the math because i wanted it to increase my 10% each time but after a certain point its over doubling each time
pancakePrice = pancakePrice + (pancakePrice * (pancakeValueUpgrade / 10));
this is the code/math for each upgrade
what's pancakgeValueUpgrade?
thats the variable that tracks how many upgrades you have done
if it should just increase 10%, that would just be pancakePrice = pancakePrice + pancakePrice / 10, or pancakePrice *= 1.1;
you're using the current value as a base, rather than the initial value
oh thanks
though, that would exacerbate your issue
if a geometric series is how you want your prices to scale, then your economy should be a little south of that same series
(if you have a single upgrade, that is; if you have multiple upgrades, you should make it drop off faster than prices)
Yooo does anyone knows any tutorial or something to make a controller settings in unity?
Like change the input of something
have you tried googling for one
All the videos are for creating the main menu
And the creating settings menu video does not have the input settings
Anyone here willing to have a look over my character controller if I tell them what's up? Been stuck at an issue for over 3 days, asked help in 3 different discords, asked help in 2 different reddits, asked several friends, asked 3 different AI's. I just cannot figure it out and I'm stuck.
I know having a look at an entire character controller is daunting. I could also send relevant parts. But seeing the entire code will probably give you the entire overview of it.
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
read the last point in particular
@slender nymph I already did send in my question before. See the thing I'm replying to. Perhaps I should've tagged it. Just don't have an answer to it yet. Had some helpful suggestions but they were far beyond my skill level (state machine design).
All I know is, when I remove the JumpBufferCounter and CoyoteTimer and set my jump to GetControlBinding() instead of GetControlBindingDown(), I can jump out of the water. But if I don't have those buffers and timers, you can infinitely hold spacebar and keep jumping on land.
In an observer pattern, how do you have the observers find the subject without coupling?
The only way I've found is something called a "Message Bus" but that is way overkill for what I'm doing
depends your project
the typical modes, DI, Singleton etc
Singleton is still coupling it
I agree but ideally for this project I'd want to couple as little as possible
especially in the bits I'm "showing off"
ie patterns
its not a tight coupling though
originally I didn't use observer at all and just did a C# action which was WAY simpler
wdym what are you using now ?
Observer pattern
so it iterates through it's observers, and notifies each of them
the issue is idk how to have the observers subscribe without coupling lol
uhh isnt observer just using Events?
I don't think so, but I could not explain the difference if you asked me
I'll look into it
it is, i think the only main difference is you typically DI the reference
create a bit more abstractions with interfaces n all
its jiust long winded way of saying "using events" and the Invoker doesnt care who listens
I think it may just be that the observer pattern is designed to work with OOP? So you make an observer object, rather than having an event carry the message
or something idk
idk if that makes sense
its just this
yes
yes just event observing
observer, pub/sub, and events are really the same thing
DI is mostly whats used let the Observers recieve the Publisher
unless the event is static sometimes
I think the key difference is that you can have an Observer object, but you can't have an Event/Action object?
Observer is just a fancy word for events
but you can't have a monobehaviour action for example right?
yeah its kind of semantics
for example in js, a function is an object with an internal slot, so you could make a function that also works as a monobehaviour
in java, the equivalent of "actions", lambdas, use interfaces, so you could have a class that otherwise acts as a monobehaviour but also implements Runnable
but the core of observer/pub-sub/events is just, it has a callback
you could have a wrapping object for any of those definitions, as an intermediate manager, if desired
but it's not necessary
Yooo I want to call a variable (which is a KeyCode) from other script but it doesn't work
public System.DEFAULTmov movement;
public void Select(string name)
{
if (name == "A")
{
movement.right = KeyCode.A;
}
}
"DEFAULTmov" is the script that contains "right" as a variable
also for future reference, !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
also note that unless you wrapped your class in the System namespace yourself it is definitely not in that namespace
that's not a unity question
Hello there. I tried to make it that a script references the object it's attaching. The script I use is for making the text fade out, but when I test it, it doesn't grab the object as the game starts, and I don't know what did I do wrong since there's no error.
https://paste.mod.gg/masrwycqerwr/0
I want to do it this way so I wouldn't have to reference it in editor or by name/tag. It'll just reference the thing it's on
A tool for sharing your source code with the world!
Show the inspector
What if you put 'Debug.Log("A Value: " + aValue)' in the update function? What do you get as a result in the console? Does it decrease there?
That's not the problem. The problem is that the Text variable doesn't automatically get the reference object
Wrong type? TextMeshProUGUI
Oops my bad. Maybe try to get TextMeshProUGUI as it is on the UI and not in the regular scene?
Or TMP_Text if you're uncertain
It works but the text doesn't fade out as the value decreases
What if you print out the value like I posted? Does it decrease there?
If statement is likely false or fade rate may be zero in the inspector
In this image, active is false
I made active true and it doesn't make the text fade
The value changes, but it doesn't seem to do anything to the text itself
Do you ever apply the value to the text's alpha?
I should've. Line 19 has aValue set to text alpha
oh wait, I think I found a problem
That would only copy the alpha value
You would need to apply that variable's value back to the text's alpha to modify the text's alpha value
Like Dalphat is saying, you are setting aValue to the value of the color. You need to do it the other way around, as you want to set the color value to the aValue.
It wouldn't because Start only occurs once
Just update the value after changing it in Update
It works now
Tho I don't know why I can't just set aValue to it directly as it said it's not a variable. I have to write "text.color = new Color(text.color.r,text.color.g,text.color.b,aValue);" to make it work.
I mean, if that's a c# way, I get it, I'm just curious why it doesn't work that way, and why I have to put "new" on Color
Color is a struct (value type). The property returns a copy of the color only.
You'd need to assign color an entirely new color to modify it as modifying the alpha of a copy from the getter will not modify the actual color on the tmp component.
If color was a field it would be fine but it's a property (function that pretends to be a field)
Alright, what is a property? I know what is a field, but I'm looking up what's a property and it doesn't really explain me
Anyone here knows how to make recording cameras? like content warning does? i know few APIs, but they're all paid, is there any free option?
I havent played the game, but what exactly does recording do ?
like a video ?
a property is a method (or 2) in disguise, to be used like a field, but optionally with extra logic
Yep, you basicaly use the video camera to record a video and save it at the game files
so, my goal was to make it when the player is using the camera, the player can record 15 seconds, and then after a cooldown he can record a little more
In my game you are basicaly in a team of reporters trying to prove the existence of ghosts, then you record and take pictures of proofs, to then manually create a headline for it, and choosing the best videos you made to add at the headline
hmmm I wonder if something like Unity recorder has some type of inGame api
apparently not. You most likely need to find a free / open source lib compatible with .net 4.x
found this https://github.com/keijiro/FFmpegOut
but there might be more
like https://github.com/videokit-ai/videokit?tab=readme-ov-file
Is this where you ask questions about coding?
did you read the channel description ?
oh lol
I just started coding and I am following this book and its showing errors in my code when following the book.
you have a very minor syntax error
look carefully at your Method declaration
the first red underlined is usually cause for the rest
Ahhh I see it
remember ; means end a statement, not very good thing when you're opening a code block/body after
Gotcha, thankyou
hey uhh im making an end level thingy that takes you to the next scene but im getting an error here is my code
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
You're missing one e in manag__e__ment lol
nice
im an idiot
and this is why we share code with Links/Codeblcok and not screenshots
thanks so much
But please do follow nav's advice
got me good
If you configured your ide it would've told you that namespace didn't exist
yeah it would underline it red
make sure you have a configured IDE its also required to get help here next time
i didnt know you had to configure ill do it now thanks!
your sanity will thank you
i hope so especially sicnce i hate spelling on pc and capitalisation😭
with it configured, even if you dont capitalize it MOSTLY captures / you press tab and its putting the one you want
could anybody offer me some help rq with the animator panel? im tryna use a simple ai wandering script but the animal never enters the idle state or the idle animation.
not much do go off this
you mentioned the problem in a way, but we cannot see anything you've done, setup or code . We can only do random guesses, not very useful lol
thats my script but i think its mainly the animators problem
since i just took these from online
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
show the actual transition conditions
so its going into Run but doesnt come back into idle ?
Debug.Log the part of the code where it supposed to hit the
animator.SetBool("isRunning", false);
for good measure I'd also remove this 👇
and also you should observe the animator while selected (select gameobject with animator) to see what the transitions are doing
its not transitioning back to idle at all its just repeating the run animation
yes I understand the problem, but you have to figure out why
first step would be debug.log
looking at the animator would also show you if the bool was ever triggered once
it was this. thanks. ts happens considering im just following a yt tutorial on how to make a game
tutorial is fine if it works and you can follow it exactly.
but imo you should do the structured Unity courses first in !learn site
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
they cover everything a bit more clear because well they made the software lol
nah some rando youtube video must be better! /s
is invoke no longer used? Edit:nvm me
its for a college assignment so im kind of learning as i go instead of starting small but they didnt really give us enough time to learn unity tbh
You mean Invoke/ InvokeRepeating . Generally you wouldn't use those. If you need a delayed action you're better off with a Coroutine
What's the best variable type to store and display a table like this? it must be dynamic, as different instances of the class will have different collumns on the table
a list of some custom object that has the properties you want on it
i'll take a look at coroutine for sure, thanks
hmmm wait, wym? how exactly
i mean exactly what i said. you create some type that contains the properties you want to represent the columnds of your table and you just create a list of that
Oh, ok, but I don't think that works. Each instance of the class will have tables with different collumns
hey so i have a scriptable object (i think thats what its called) and i want to during the game change one of the values but for some reason its saving it
pancakeData.Delay = Mathf.Max(pancakeData.Delay * 0.90f, 0.1f);
is there a different way to code it or smth so it doesnt save the new value
then make it generic
this is expected behavior in the editor. modifying assets will persist those changes in the editor
I can have an instance of my class class called Cleric with a table that has the collumns Level, PB, Features, Channel Divnity and Spell Slots 1-9. Rogue on the other hand would have a table with the collumns Levels, PB, Features and Sneak Attack Die. etc
then should i just make a different variable that just on start function copies that one
yeah, or just in the editor instantiate a clone of the SO and use that in its place
hello i was wondering if it was worth it to follow this tutorial to make a radar chart or if i should use a line renderer wich would be easyer and faster i think; https://youtu.be/twjMW7CxIKk?si=gcMT9-aq7TTL4RVN
YouTube
✅ Get the Project files and Utilities at https://unitycodemonkey.com/video.php?v=twjMW7CxIKk
Let's make a Radar Chart as used in RPGs to display Character Stats.
We're going to create a very nice clean Stats class and a script to display it. It will be shown using a custom Dynamic Mesh drawn in the UI.
The code is very easy to modify to add mor...
if it works for you needs then follow it. If you think you can solve it another way easily, then try it. I dont think many people here will watch a 40 min tutorial to tell you if it is worth it.
The only thing is code monkeys tutorials are generally not that good but maybe it'd introduce you to a new concept
alr thanks!
Unfortunately this video kit ai, has what I want but it's monthly paid, and I can't afford it, and the ffmpeg is just taking screenshots and making a video out of it, which impacts performance a lot unfortunately
it has a free tier, also thats pretty much what video is
a series of pictures
have you tried to use ffmpegout before assuming there is a big performance impact ?
Yeah tried it yesterday sadly
It worked, but the performance was like cut in more than half, I was getting 80 fps in a 3070, where I used to get 340
how were frames captured and sent to ffmpeg?
bummer. there are probably other solutions, haven't looked too deep into it
Rn I don't remember exactly cause I deleted the files, but I could set it up again, maybe it was configured wrong or something
i was wondering what the perf was and how it was done incase it could be improved. ffmpeg offer native libs which should be used
Btw using this you think I would be able to put sound at the video? Like both the mic and the ambient sounds
Cause it's kinda just a sequence of screenshots
ngl i dont know how to record sound "playing" in unity unless an audio listener can output its current state
Well chat gpt told me content warning used videokit
50$ a month is insane
why is this a subscription
what isnt a subscription these days..
I ask the same question
well i suspect such a package isnt super secure 😉
Well it needs an access key so 
imagine if its always checking at runtime if you have a subscription still and breaks ur game when you stop
Yes, at the documentation they pretty much say that this would happen if you stop the subscription lmao
yea thats mental id never ever use such a thing
Yeah, I'd even pay 150 dollars for it, if it was an asset or something
But monthly subscription? Hell nah, that's the reason I never played wow lmao
you also asked a spam generator what tool a game uses. maybe just try contacting the game developers themselves and ask
more likely it is a custom solution
if you know what you're doing with external libraries, you can get this done
even just skimming through, it doesnt seem like this is all that impossible to write yourself
also not clear here, this can be an issue of you trying to stitch it / encode while still recording or something?
or perhaps wrong settings were chosen
Yeah...I'll set this up again when I get home and I'll see if it was a problem of settings or something
kinda curious to try this myself later, see what i can cook
Sad part is that this is probably one of the 2 core mechanics of the game so I really need to get this right lol
look at libavcodec but i cannot find any good documentation apart from this: https://ffmpeg.org/doxygen/6.0/group__libavc.html
in an ideal world you can capture and stream frames directly to be encoded
Well if there's only this documentation, I'll see if chat gpt can help with it
try but expect it to make up shit
its common with these good c/cpp libs that their documentation is trash and soo hard to read
(libcrypto im looking at you ✊ )
its very rare GPT suggests something useful or that even exists
Yeah, thats why gpt is most likely my last resource lmao
Search for some open source that uses it on Github
This is their "doc page": https://ffmpeg.org/libavcodec.html
has fuck all info
Surely there's something that lets you capture a bunch of frames from a camera, then you can stitch those together with ffmpeg
I wish I had contact with any devs of content warning but I can't even find they twitter lmao, only the publisher
hope you can figure out something but plz try to use the lib instead of writing files to disk and invoking ffmpeg as a process many times
Yeah, the player will have the ability to record only 15 seconds per time so this shouldn't be a problem I think
Yess
Oh I see why it's a subscription, apparently they offer you an option to save your videos on cloud, but why wouldn't they allow you to even save videos at the own project files at the free option, you can't do anything lmao
And also some ai bs
Hey I want to display rare unicode charcters in unity
I figure the best way to do this is to import a font
since just putting the unicode character in the string in script doesn't seem to work for the rare ones
but I have no idea how to make a font
like this kind of thing
but arbitrary unicode characters so I can mix and match them programatically
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
You need to say what you need help with. What is the issue?
i found the bug but im not sure how to solve it using an AND.
my issue is that
you can use stamina and everything just fine however you'll never regain it until you make IsStaminaBeingUsed false which is impossible unless you get your stamina to 0 which isnt what i want
i want it so you regain if you just let go of shift which is what i have set up
-# Also its Line 111 - 123
@obtuse pebble
"if (stamina <= maxStamina)" So you will be recharging stamina even if it is equal to max stamina. I am assuming this is not intentional?
yeah your supposed to earn the max stamina (as in including that number)
Alright, I am pretty new myself, but I don't see you ever setting isStaminaBeingUsed to true.
i dont think that has anything to do with the bug though
because everything seems to be fine its only that one bug with never being able to regain without reach 0 stamina
why does this not work? i'm sure i'm doing everything correctly
Whats the exact issue?
well i can only jump once, I'm not getting the debugs of the Ground Hit, or the Jump available either.
i want to make sure i cannot jump before i hit the ground
Double check that the ground has the "Ground" tag
it must be the exact spelling
but i'm not getting the ground hit debug
Oh
which is out of the if statement
I doubt it's the tag, as the "hit ground" debug log does not trigger either
i see now
yes
you're using OnTriggerEnter, which implies the colldier is a trigger
yeah
i was about to say that
oh ffs
you can either use OnTrigger or OnCollision Enter
OnCollisionEnter is what im supposed to use ye
but for on trigger double check that it has IsTrigger = true
vertx also has a good page for debugging basic physics issues https://unity.huh.how/physics-messages
and your colliders likely shouldnt be triggers for this
its basically the same but i think its collider other in the parentheses
alright thank you, OnCollisionEnter was the correct function to use. it works now. sorry about begin blind xd
idk
Dont worry about it, we all make mistakes... trust me
trigger is smth you go through. iirc instead of colliding with it
The Item Assets script shows me null and I don't know why, I'm trying to spawn an object but it always shows me that ItemAssets is null and I don't understand why.```using UnityEditor;
using UnityEngine;
public class ItemAssets : MonoBehaviour
{
public static ItemAssets Instance { get; private set; }
[Header("ItemModels")]
public GameObject PfSword;
public GameObject PfAxe;
public GameObject PfLance;
[Header("ItemImages")]
public Sprite SwordImage;
public Sprite AxeImage;
public Sprite LanceImage;
private void Awake()
{
if (Instance == null)
{
Instance = this;
}
else
{
Debug.LogWarning("Hay más de una instancia de ItemAssets en la escena.");
Destroy(gameObject);
}
}
if your ground in the future has slope, you also might run into issues in the future. right now if they touch any ground at all they can jump, no matter what the slope is
Strange, im not to sure because it looks like your more advanced than me
you really dont need to comment if you cant solve an issue. there are like 100k people in this discord, itd be chaos if everyone replied like this
lol
awake probably hasnt run yet by the time you try accessing it. which object are you trying to acces it from
well, its all good for now as its my second day and i made the bracky game and learned that few bits of coding, now i'm trying to make that jump acess only via a collectiable on the second round without any online vidoes or stuff. so lets see how it goes xd
You can try in #archived-code-general since its more advanced
why are you replying to my message on that? and also their problem is not advanced at all
its really quite beginner
as long as the ground remains simple then the current code is fine 👍 one "issue" thats really an exaggeration just to make this clear: if you have ground above the player, and they jump into it, they might be able to spam jump forever against it
My unity just Crashed... Turns out you should never write a while loop before checking that its not gonna run indefinitely
gotcha, will keep that in mind
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
please delete those and use a link to paste it
also that first code isnt even valid c# so maybe check if u have compile errors first
didn't use the thing well?
aaa ok should I upload them as a file?
read the bot message, and even my message below it... "use a link to paste it"
there is the large code block section
Share the URL
A tool for sharing your source code with the world!
Taking screenshot is just.. missing whole point
none of these methods use unitys methods like update, so something must be calling these. Try to follow down the path of whats calling SpawnItemWorld, because you're likely doing this during or before awake
your problem is just this code is running before ItemAssets.Awake is running
aaa ok thanks I'll let you know if the problem is solved
Ready, it works for me now. Thank you very much.

I should probably put this in general but theres an active convo in there that i don't wanna disrupt
I have a custom generic class called ExtendedMatrix2D<T> which is basically a T[,] with a bunch of helper functions built into it.
I have a ExtendedMatrix2D<ScriptableTile> instance and a function requesting a ExtendedMatrix2D<ScriptableContent>.
ScriptableTile derives from ScriptableContent but when I attempted to pass in my ExtendedMatrix2D<ScriptableTile> to implicitly downcast it it doesn't like it.
Is there any way I can support this kind of implicit downcasting of my ExtendedMatrix2D or is that not really how this is supposed to work
(the line in particular for example)
protected override ExtendedMatrix2D<ScriptableContent> GetMatrix() => currentLayout != null ? currentLayout.TileMatrix : null;
X is a subtype of Y does not correlate to A<X> being a subtype of A<Y>
Yeah I get why it's happening but just curious how I should go about handling this
It is generic, just currently defined as ScriptableContent. I'd ideally prefer to downcast it like im trying to in this context but if that's not how i should be handling this kind of thing im open to pivoting
(as i wanna use more deriving types and it doesn't need to be anything more than a scriptablecontent for this stuff)
was hoping there was some cool c# magic i could implement into ExtendedMatrix2D to instruct it on how to downcast stuff ezpzily
generic classes are invariant in c#
for T ≠ U, A<T> is not assignable/a subtype of A<U>
so downcasting the generic won't work
ExtendedMatrix2D<ScriptableTile> and ExtendedMatrxi2D<ScriptableContent> are disjoint types, so if your function should handle both, then it should be generic
unity's c# compiler does not support covariant return types.
https://docs.unity3d.com/6000.0/Documentation/Manual/csharp-compiler.html
ah wait, i don't think that applies. I assumed you were having trouble with changing the return type for your overridden method which is what covariant return types is referring to. Chris is right here that the generic class is invariant
depending on your actual needs with this you could create a generic interface that supports covariance and use that for the variable that you are assigning to
i see i see
I tried being big brain and making that function generic in a way where the implementation of this function defines the constraint rather than the generic in the function directly but no dice there either
protected abstract ExtendedMatrix2D<A> GetMatrix<A>() where A : T;
im sure it makes sense but i do not like when VS tells me this aha
wait hold on what are you trying to do here?
this is a method on the extended matrix class?
and you're trying to get this as a different type?
There's a lot going on here, wasn't sure how much I needed to provide.
I have a ScriptableRoomLayout class that contains a couple ExtendedMatrix2D's including ScriptableContent, ScriptableTile and ScriptableEntity matrixes.
right now im trying to use them in a custom EditorWindow which is a TileMapEditor<T> that I want to generically handle rendering and modifying 2d arrays.
This TileMapEditor<T> stores a reference to the ExtendedMatrix2D it's targeting which it's provided by an abstract class (in this case ScriptableContentEditor : TileMapEditor<T>
I guess i probably don't need to store the defined matrix in TileMapEditor though and can probably just rely on constantly asking for it via a property or something
which frees me up abit
maybe
i think ive maybe rubber ducked myself a little
Hello, so I was following a tutorial for a pickup system that was made for Unity 2022 and I'm using Unity 6, the problem is that the script doesn't work, i have re-written it, changed some variables and options, added debugs and can't find a reason to why it doesn't work
I have also made an exact same version with the new input system and still has the same issue
Maybe something about the Rigidbody or forces changed in Unity 6
hey everyone, I am new to unity and I am facing a problem,
I have several tutorial popups, dialogues, and map triggers in my game that should appear every time the game starts fresh but should not reappear after the player dies and restarts.
Current Issues:
When I first start the game, all dialogues, popups, and map triggers appear as expected.
After the player dies and restarts the game (without closing it), these dialogues and popups do not appear again(working fine).
If I fully close and reopen the game, the dialogues and popups should appear again (this is not working ).
how can i fix this please?
!code 👇
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
Show relevant code 👆
using UnityEngine;
public class GameStartManager : MonoBehaviour
{
void Awake()
{
if (!PlayerPrefs.HasKey("GameLaunched"))
{
PlayerPrefs.SetInt("GameLaunched", 1);
ResetTutorialData();
}
}
void ResetTutorialData()
{
Debug.Log("Resetting tutorial state...");
PlayerPrefs.DeleteKey("HasSeenPopups");
PlayerPrefs.DeleteKey("HasTriggeredMap");
PlayerPrefs.Save();
}
}
private void OnApplicationQuit()
{
PlayerPrefs.DeleteKey("GameLaunched");
}
OnApplicationQuit doesn't work in the editor if thats where you're testing
so if I build the game and run then it will work ?
and if I use alt+f4 to close the game will it call onApplicationQuit()?
I think so.. one way to be sure 
You don't need player prefs for any of this. Just use a static variable
yea playerprefs is overkill and overcomplicating it
If you have domain reload disabled then you just need to reset the static variables as normal in that workflow. Otherwise they will be reset each time you play
I believe a static bool would work in that scenario... at least what I use for my loading screen
what's the issue? we can't help much if we don't know what to fix
using UnityEngine;
public class TutorialPopup : MonoBehaviour
{
[SerializeField] GameObject popupPanel;
[SerializeField] MovePlayer movePlayer;
[SerializeField] LookMouse lookMouse;
[SerializeField] GameObject canvas;
private static bool hasSeenTutorial = false;
void Start()
{
if (hasSeenTutorial)
{
popupPanel.SetActive(false);
movePlayer.enabled = true;
lookMouse.enabled = true;
canvas.SetActive(true);
lookMouse.LockCursor(true);
return;
}
popupPanel.SetActive(true);
movePlayer.enabled = false;
lookMouse.enabled = false;
canvas.SetActive(false);
lookMouse.LockCursor(false);
}
public void CloseButton()
{
movePlayer.enabled = true;
lookMouse.enabled = true;
canvas.SetActive(true);
popupPanel.SetActive(false);
lookMouse.LockCursor(true);
hasSeenTutorial = true;
}
}
like this?
Hey yall. This is probably a pretty simple question. As the code reads, I am trying to get the child of a gameobject with the selected tag. I dont really understand what the shown error means. Could someone explain the error, and or how to fix it?
you're calling it on an instance and Find() is a static method. you should use transform.Find
Like such?
well you'd need to add .gameObject at the end I believe
@nocturne oak yeah you can think about it like this:
Game-wise:
- Scene is a snapshot of a "world" at a specific time
- GameObject is an object that resides in the Scene
- Components define a GameObject's properties and behaviour in the Scene
- All Components attached to a GameObject are part of the same object
Code-wise:
- Each of [
GameObject,Transform,Components] are differentobjects (in the PC's RAM). Transformis aComponentthat allows the engine to grab theGameObject's location.- When you wanna cache/store a reference to a variable of type
GameObject, you can't assign itsTransform, because they're different objects.
@exotic jacinth also you can make it so that the onapplicationexit works in the editor too, i think it's a preprocessor directive + an extra line of code, look it up you'll find it easily
hello all, i have an issue with colliders.
I have a set of interactions that require the player capsule collider to have isTrigger = True. I have also been putting the Freeze Position.y = True as well up to this point. Now i want to implement a jump mechanic. When I set FreezePosition.y = false the player falls through the platform, ignoring the platform's box collider.
Can anyone help in implementing the jump mechanic? Please let me know if any information is missing
public bool inAir = false;
void OnCollisionStay(Collision collision){
if(collision.gameObject.CompareTag("GroundTag")){
if(Input.GetKeyDown(KeyCode.Space) && inAir == false){
playerRB.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
inAir = true;
}
inAir = false;
}
}
Triggers do not collide with other objects or send OnCollision events.
yes that was the issue. I did find a workaround by using two different colldiers - a capsule collider to handle the trigger interactions and a box collider to detect ground collision. Works now
thanks for your time
`private void AttackPlayer()
{
agent.SetDestination(transform.position);
Vector3 directionToPlayer = player.position - transform.position;
directionToPlayer.y = 0;
transform.rotation = Quaternion.LookRotation(directionToPlayer);
if (!alreadyAttacked)
{
Rigidbody rb = Instantiate(projectile, transform.position, Quaternion.identity).GetComponent<Rigidbody>();
Vector3 shootDirection = (player.position - transform.position).normalized;
rb.AddForce(shootDirection * 32f, ForceMode.Impulse);
rb.AddForce(transform.up * 5f, ForceMode.Impulse);
alreadyAttacked = true;
Invoke(nameof(ResetAttack), timeBetweenAttacks);
}
`
Enemy's bullets going up instead of going to player. I think it's about math and I'm not good at it. Can someone help me?
Hey im currently working on isometric movement i was wondering if anyone here also had it and could help me with it
So what's wrong with movement?
When i press W or S the player moves forward or backwards diagonally (North-West, South-East) and for A and D it moves along the other diagonal (North-East, South-West) instead of moving up, down and side to side
Basically shifted 45 degrees counter clockwise
Can you send codes?
`void Move() {
// Convert local input to world space
Vector3 movement = transform.TransformDirection(input) * speed * Time.fixedDeltaTime;
// Move the player based on the calculated movement
rbody.MovePosition(transform.position + movement);
}
`
Change Move function.
to this.
This is because you use the input vector directly in the global domain (world).
Anytime.
Still need help.
I now am encountering issues with uneven speeds. When 2 keys are held down the speed is faster than when one is pressed down.
Can you tell me where to attach the script in the timeline, on this track?
not a code question but the question is vague anyway
You can use Vector3.ClampMagnitude to clamp your input to a length of 1, for example
Thank you
Does anyone know how to use this ?
It appears you're meant to use Animator.SetTrigger method to call animation states that correspond to the trigger parameters
This is not how animator controllers are meant to be set up, as there's no advantage to using one like that at all, but it should work
Can I directly DM you or add you as friend ? to teach me how to use it or refactor it ?
how do i fix this????????????
We are not collaborating so preferably not
You can use it as is (or skip it and use Animator.Play instead), but refactoring should done with a clear purpose
To do that you'd have to study and learn the animation system from the documentation first, then if you have specific questions post them in #🏃┃animation
Okay, thanks.
Also when you find third party tutorials for the Animator, you unfortunately have to be skeptical about them
A lot of them are made by people who never fully understood the system and instead recommend you operate it with custom code that unnecessarily recreates the state machine and transition functionality that already exists
Prefer the documentation and Unity's official tutorials as your primary source
how can i wait 1 frame in coroutine?
yield return null;
not WaitForEndOfFrame()?
that waits for the current frame to complete, yielding null waits for the next frame to start
whats the difference in practice
yielding null has additional time between frames?
No.
oh so it waits until the frame is "shown", and yield null waits until the next update call?
right before the frame is shown
hi
where can i ask a question about the debug draw mode in the unity editor?
what the
what did you do man how is he dancing and going up!?!?!?!
idk i tried adding it a movement script
i don't know 3d but could you please tell me what did you do?
a movement script?
then why is he dancing😆
alrgiht never mind
idle
can you give me the code?
ok
maybe its because the ragdollcontroller
no
okay then idk
i have never heard that word in my life
"ragdollcontroller"
IDK sorry
do you know this @frank beacon
i dont know about 2d ssry
no i mean where can i ask it in this server
like the thing that makes the player fall like a human and not a statue
#💻┃unity-talk probably
@frank beacon what's your question
tysm!❤
a video is far too little info to go off of
what do you have controlling the position of that object?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ragdollControl : MonoBehaviour
{
private BoxCollider mainCollider;
private Animator anim;
Collider[] ragdollColliders;
Rigidbody[] ragdollRB;
void Start()
{
mainCollider = GetComponent<BoxCollider>();
anim = GetComponent<Animator>();
ragdollParts();
RagdollOFF();
}
void RagdollON()
{
anim.enabled =false;
foreach(Collider c in ragdollColliders)
{
c.enabled =true;
}
foreach(Rigidbody rb in ragdollRB)
{
rb.isKinematic =false;
}
mainCollider.enabled =false;
GetComponent<Rigidbody>().isKinematic = true;
}
void RagdollOFF()
{
foreach(Collider c in ragdollColliders)
{
c.enabled =false;
}
foreach(Rigidbody rb in ragdollRB)
{
rb.isKinematic =true;
}
mainCollider.enabled =true;
anim.enabled = true;
GetComponent<Rigidbody>().isKinematic = false;
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "colisionador")
{
RagdollON();
}
}
void ragdollParts()
{
ragdollColliders = GetComponentsInChildren<Collider>();
ragdollRB = GetComponentsInChildren<Rigidbody>();
}
}
i think
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
there's nothing here that controls the position of the object though
oh
does your animationclip change the position or something
using UnityEngine;
using TMPro;
public class Movement : MonoBehaviour
{
public Rigidbody rb;
public float Walkforce;
public float Climbforce;
public float Descendforce;
public TMP_Text TimerText;
public TMP_Text SpeedText;
private float playerSpeed;
private bool isTimerRunning = false;
private float TimerTime = 0.00f;
void FixedUpdate() {
if (Input.GetKey("a")) {
rb.AddForce(-Walkforce, 0, 0);
isTimerRunning = true;
}
if (Input.GetKey("d")) {
rb.AddForce(Walkforce, 0, 0);
isTimerRunning = true;
}
if (Input.GetKey("w")) {
rb.AddForce(0, Climbforce, 0);
isTimerRunning = true;
}
if (Input.GetKey("s")) {
rb.AddForce(0, -Descendforce, 0);
isTimerRunning = true;
}
if (Input.GetKey("m")) {
isTimerRunning = false;
TimerTime = 0.00f;
}
if (isTimerRunning == true) {
TimerTime += Time.fixedDeltaTime;
}
playerSpeed = Mathf.Abs(rb.linearVelocity.z);
Debug.Log(playerSpeed);
TimerText.text = "Time - " + TimerTime.ToString("F2");
SpeedText.text = "Speed - " + playerSpeed.ToString("F2");
}
}
guys why is playerSpeed 0 when the cube is moving?
all the script works so it's not an issue, but playerSpeed is 0, thus SpeedText is 0, please help
Because you're only reading the z axis component which is 0
You probably want linearVelocity.magnitude
oh okay, thank you very much! i wont crosspost from now on
you should try to use input axis instead to simplify your input -> force application. Having an if and special force for each key is not a great idea
any good tutorial should do this anyway
thank you very much!
bonus tip! String interpolation lets us create strings with stuff in them easier: TimerText.text = $"Time - {TimerTime:F2}";
Hello everyone!
can someone help me understand aspect ratios in unity?
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
especially that last point
I positioned my UI based on the 1920x1080 aspect ratio
yeah one sec
trying to get a screenshot
but then when I build for PC or WebGL all the UI is messed up and in a different location
the health bars got really tiny, and the bottom boxes aren't even visible
Read the documentation pinned in#📲┃ui-ux to learn how to correctly anchor and scale your ui
how do i set layer mask to "nothing"? when i try to set it to 0 it sets it to default
all has to do w/ the anchors and being relative to the parents
once u have ur layout laid out.. grab the window and do some squeezy streetchy
where ?
you cannot change the default layers
i just use a layermask exposed in inspector
thats what i just did and now i wonder if theres a better way to do this
so once you set it to scale with screen size you have to manually resize everything? it stretched everything weird when I did that
yea.. if its stretching everything ur anchors are bad
layer 0 is Default
layermask 0 is nothing
LayerMask myMask = 0;
it sets it to default
if ur wanting Nothing why even use a layermask at that point? lol
culd just use a boolean...
ifUseLayerMask == true -> now use the layermask
ifUseLayerMask == false -> just use code w/o a layermask
I'm still not sure I understand. I changed all the anchors of the rect transforms so none of them were stretch and then I put the canvas to scale with screen size and it still put them off screen and stretched them, so I changed them again and built and it's exactly the same as it was
are u anchoring them to the center?
how do I anchor them so that their positions on the screen are fixed
u should anchor to whichever corner is closer..
can't say w/o context (lookin at what component is using that anchor..
and how its setup in heirachy.. anywho ^ like here.. the UI i have in the bottm left.. well, it should be anchored to the bottom left.. (its offsets are left and bottom)
for the branding logo its top right.. soo ih ave it anchored top right.. w/ its offsets being from the right and the top
etc etc
take these two health bars that are supposed to be in the top left
when I build like this, they are extremely tiny suddenly
and they're closer to the center than the left
even though I selected top left in my anchors
this one is anchored to the top left.. which is good..
then why do they change size in the built version?
and move from their position in the corner?
in unity
in build
well its Rference resolution is 800x600..
ohhhhhhhh
I installed URP into my project, assiged URP pipline asset. I created a standard surface shader, but when I open it it is all errors. How do I make coding a shader compatible with URP?
u find out u let me know 👍 ..
i typically end up trying to convert them to Shader-graph
with hit or miss results
I made a shader graph and it isnt compatible
Make your shaders Scriptable Render Pipeline Batcher compatible.
This step by step video tutorial will show you how to convert a custom unlit Built-in shader to the Universal Render Pipeline (URP). It includes a Unity project to follow along with that you can get here: https://github.com/NikLever/Unity_URP_Videos
Get the free e-book: Introduc...
ok I changed the resolution to match 1920x1080, but the built version is exactly the same
is it something to do with one of the other settings like screen match mode?
thanks
good luck..
urp lit shaders are a pain to do customly, use shader graph as much as possible
- doesn't sound like a code question, #💻┃unity-talk
- what's the difference in question?
Oh right sorry
@rocky canyon bro i'm trippin. the build was using the wrong scene file. thanks for your help, your explanation fixed it
jeez..
i knew something smelt fishy
why is my vs code not showing any options like in the tutorials
!ide
also the tutorial is using visual studio not vs code
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
If your IDE isn't providing autocomplete suggestions or underlining errors in red, then it needs to be configured.
tysm i'll try
how do y'all learning to code 😭 i just cant wtf
patience, time and practice
there are resources in the pins
Does Unity use the flyweight pattern "by default"? Like when you assign a reference to a prefab and instantiate based on it?
Or do I not understand it correctly
When you assign a reference to a prefab and instantiate it, Unity creates a completely new instance in memory. Each instance has its own copy of all data and components, so it doesn't automatically share memory the way a strict Flyweight pattern would.
Unity does do optimizations that resemble in it certain cases..
- meshs, textures, and materials are shared ie. Multiple tree's using the same MeshRenderer will not duplicate the mesh data in memory..
- scriptable objects sorta act like flyweights.. ie. can store shared data that multiple GameObjects reference w/o duplication
- object pooling ie. object pooling achieves a similar effect by resusing objects instead of constantly creating/destroying them..
how would i go about making an throwable that goes through the enemy but still registers as a hit and isnt trigger(so it can interact with the scene)
also i cant destroy the enemy onhit because of a death animation
Use a different Collider for the scene interaction as for the enemy interaction.
Use layer based collisions to set up the interactions
wouldn't layer collision mean that the enemy throwable interaction is ignored?
I don't know the details of your setup but the answer is you wouldn't ignore whatever collider you need to interact with for whatever specific interaction it's needed for
I'm not sure what the enemy throwable interaction is exactly
its a saw that cuts the enmies in half but i want collat kills
so it shouldnt bounce off the enemy like any other prop
this with a little tweaking worked thanks!
I'm new to programming on unity, does anyone have tips on starting?
there are beginner c# courses pinned in this channel and the pathways on the unity !learn site will teach you how to use the engine
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
a question what's wrong in these pieces of code? after hitting the object or triggering it which has the first picture script on it. i'm able to jump but only once
- !code 👇
- where do you change the value of isGrounded
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
without the canjump, the code works though
oh and i do change it
that's the last piece of code, ig i should have shown all the ones instead
don't use screenshots for code, see the bot embed above
then you are setting that to false again somewhere else because nowhere in the code you've shared (incorrectly) have you assigned anything but true to it
alright, i will keep that in mind for the future but for my problem atm that's all of the code
share your code as text
the full class
!screenshots
No
Be mindful, if someone requests your code as text, don't send a screenshot!
in the images on the last picture, isgrounded = false when the jump() is called
last time i checked isGrounded is not canJump
send your code as text.
A tool for sharing your source code with the world!
use your IDE to find all references to that canJump variable since you claim that without that variable it works correctly
i have 3 references yes
Hi guys in my game I made I have text in the top right corner but when I build the game and play it the text goes more to the middle and is not in the spot where it was like in the editor anymore. Any tips to fix taht please?
and which one is setting it to false
when i first make it public bool canJump = false;
then it should work with or without the canJump variable because that wouldn't be the issue
your UI is not dynamically scaling to different resolutions
documentation pinned in #📲┃ui-ux will cover how to anchor and scale UI for different resolutions/aspect ratios
Thank you
Thank you
okay, i saw the problem, since i'm working in scene 2 and had made a ground prefab before making scene 2 it didn't have the tags correctly. my bad
then how tf did you come to the conclusion that without the canJump variable it works?
i was testing in scene 1 😭
man i started learning unity like 3 days ago so mb few things still confuse me
This makes a lot of sense. Thank you highly! So many people will see me asking questions like these, and just send me a condescending link to the first C# course on Debug.Log Thank you highly for your proper assistance my friend 🙏
it worked fine before i put in the images but now it's not responding(not going to the game), tysm
I don’t think anyone intends to come off as condescending, It’s just that a lot of people come here to just get a solution to a specific problem, If you ask about how specific things work to understand them better people are generally keen to give you answers like that 🙂
not a code question
your Image / panel is covering the buttons or BG cant tell from hierarchy if its in canvas lol
anyway in UI hierarchy is the order of rendering, Last = OnTop
tysm
This is so confusing, i have this code
public static List<Vector2> pointsAt45DegreeAngles(Vector2 center, float radius) {
List<Vector2> points = new List<Vector2>();
for (int angleDegrees = 0; angleDegrees < 360; angleDegrees += 45) {
float angleRadians = angleDegrees * Mathf.Deg2Rad;
float x = radius * Mathf.Cos(angleRadians);
float y = radius * Mathf.Sin(angleRadians);
points.Add(new Vector2(x, y));
}
return points;
}```
when i read the code after i get this, why? its just a simple 0 to 360 degree cos / sine wave, why is this so confusing
i should get 1, .5, 0, -.5, -1, not .71 and -.71 (Input radius is exactly 1)
Isn't that how it's supposed to work
Vector of (1, 0.5) would have a magnitude of more than 1
but you can have a vector of 15 and 260 and its still good
Don't know what you mean by that
(0.71, 0.71) is a vector2 with a magnitude of 1. you can normalize (1,1) and get the same exact thing
I'm saying, for the purpose of getting the sine / cos wave of a circle, shouldnt the output be (1,0), (.5, .5), (0, 1), (-.5, .5) (-1, 0)
That would be a diamond
so if i input into a vector(.5, .5) i get a vector with (.71, .71)?
If you normalized it
But you're not ever at any time getting .5,.5
why am i not get .5 on a sin wave, doesnt it intersect .5 at 45?
could someone help?
https://pastebin.com/rQxjgQLh
The directions are kinda based on how camera is rotated, sometimes the z or x - even tho i move towards left, it goes the other way around
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 take the values from the sin / cos waves, and then create a vector2, i dont ever combine them before setting the vector 2 x / y components.
We know
A circle of a radius 1 is never going to intersect with the points at 0.5, 0.5
logically the dragging line should be exactly aligned with the line you are dragging, basically in the example it should be the same as blue, but since i probably made a mistake where we calculate it based on mouse and camera thats probably why on certain angles it does this
Also ping me, thanks
thank you all for the help, i uh, need to relearn how a circle works. i needed a diamond in code, but tried to use a circle to define the points on the diamond.
for stuff like this, i really suggest just using Debug.DrawLine or DrawRay to actually visualize what the vectors are at each step. Some of these things are kinda hard to look at code wise and tell you if some math is off.
if any vector doesnt align with what you think it should be, at least you have a starting place to confirm your math. otherwise its just you're doing 50 calculations and one is wrong
how could i integrate the draw line in it? i honestly never used that
its just a function you use and it will draw a line on your screen
okay i will go search
thanks
HOW do I make a frame independent lerp, tryna smooth my camera but the speed keeps changing based on framerate
alternatively, if you are lerping a Vector3 you can probably swap to MoveTowards instead of Lerp if you just want to specify a speed instead of a percentage
SmoothDamp is also an option depending on what kind of smoothing you want
