coolCoder
coolCoder

Reputation: 1

Python class Attribute Error even though attribute is in __init__

I'm trying to run my program:

from ursina import *
from ursina.prefabs.first_person_controller import FirstPersonController

app = Ursina()
window.fullscreen = True

class Voxel(Button):
    def __init__(self, colour, position = (0, 0, 0)):
        super().__init__(
            parent  = scene,
            position = position,
            model = "cube",
            orgin_y = 0.5,
            texture = "white_cube",
            color = colour,
            )

    def start_game(self):
        self.colour = color.white

    def input(self, key):
        if self.hovered:
            if key == "right mouse up":
                voxel = Voxel(position = self.position + mouse.normal, colour = self.colour)

            if key == "left mouse up":
                destroy(self)

            if key == "0":
                self.colour = color.white

            if key == "1":
                self.colour = color.lime

for z in range(22):
    for x in range(22):
        voxel = Voxel(position = (x, 0, z), colour = color.lime)
        voxel.start_game()

player = FirstPersonController()
app.run()

I'm using python 3.10.6 and Idle.

When I run the program it works as expected except when I choose green after I place a block it turn into white. If I spam click I get the error:

  File "C:\Users\game.py", line 24, in input
    voxel = Voxel(position = self.position + mouse.normal, colour = self.colour)
AttributeError: 'Voxel' object has no attribute 'colour'

Upvotes: 0

Views: 636

Answers (2)

Lixt
Lixt

Reputation: 227

You are using colour instead of color when using self.colour and also when calling Voxel.

You should do:

voxel = Voxel(position = self.position + mouse.normal, colour = self.color)

And:

self.color = color

The solution is to replace colour with color in your code.

Upvotes: 0

dskrypa
dskrypa

Reputation: 1108

This code appears to be using both color and colour in multiple places.

It looks like the ursina library uses the color form.

I would suggest using color everywhere in your code to stay consistent with the library you are using. It will be harder to maintain if you need to translate between spellings and remember which version is used in which place.

Additionally, even though their examples may use from ursina import *, it is not the best practice to do so because it makes it unclear what names are available in the namespace. It would be better to explicitly do from ursina import Ursina, Button, window.

Upvotes: 2

Related Questions